package com.uzai.console.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.entity.WxpubUser;
import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.common.utils.Math;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.DesensitizeUtil;
import com.uzai.console.common.utils.EmojiUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.constant.Const;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.dto.TbUserInfo.TbUserInfoIdDto;
import com.uzai.console.dto.TbUserInfo.TbUserInfoQuery;
import com.uzai.console.dto.TbUserInfo.TbUserInfoUpdateDto;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.feign.userextinfo.AlipayUserAuthDto;
import com.uzai.console.dto.feign.userextinfo.UserExtInfoQueryDto;
import com.uzai.console.dto.rocketmq.groupsendjob.GroupSendMsgDto;
import com.uzai.console.dto.rocketmq.wechatuser.SetUserRemarkDto;
import com.uzai.console.dto.user.UserUpdateMarketingTagDto;
import com.uzai.console.dto.user.useraccdetail.UserAccDetailQuery;
import com.uzai.console.dto.user.wechatuser.PriRewardRulesDto;
import com.uzai.console.dto.user.wechatuser.TimeVO;
import com.uzai.console.dto.user.wxpubuser.*;
import com.uzai.console.dto.user.wxworkuser.WxworkUserQuery;
import com.uzai.console.dto.wxpub.UpdateWechatUserDto;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.EsUserExtInfo;
import com.uzai.console.entity.es.WechatBlacklistPrv;
import com.uzai.console.entity.es.WechatBlacklistPub;
import com.uzai.console.entity.wxpubmanage.WxpubInfoEntity;
import com.uzai.console.enums.FriendRequestScene;
import com.uzai.console.enums.GroupSendJobSourceEnum;
import com.uzai.console.enums.SmsType;
import com.uzai.console.mapper.*;
import com.uzai.console.service.CommonService;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.HistoryDataFeignService;
import com.uzai.console.service.feign.UserExtInfoFeignService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.UzaiCashierServerFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.MarketingRewardsBlackListService;
import com.uzai.console.service.user.MarketingRewardsService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.service.user.WxpubUserService;
import com.uzai.console.vo.device.DeviceInfoVo;
import com.uzai.console.vo.login.LoginVo;
import com.uzai.console.vo.smscode.SmsCodeVo;
import com.uzai.console.vo.tbuserinfo.TbUserInfoVo;
import com.uzai.console.vo.user.MarketingRewardVo;
import com.uzai.console.vo.user.SysTagShow;
import com.uzai.console.vo.user.SysTagVo;
import com.uzai.console.vo.user.UserTreeVo;
import com.uzai.console.vo.user.useraccdetail.UserAccDetailInfoVo;
import com.uzai.console.vo.user.wechatuser.MinMaxCreateTimeVo;
import com.uzai.console.vo.user.wxpubuser.WxpubUserInfoVo;
import com.uzai.console.vo.user.wxpubuser.WxpubUserPageVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WxpubUserServiceImpl extends CommonService implements WxpubUserService {

    private Logger logger = LoggerFactory.getLogger(WxpubUserServiceImpl.class);

    @Autowired
    private WxpubUserMapper wxpubUserMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private UserAccDetailMapper userAccDetailMapper;
    @Autowired
    private TbUserInfoMapper tbUserInfoMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private WxpubInfoMapper wxpubInfoMapper;
    @Autowired
    private UserTypeGroupMapper userTypeGroupMapper;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private UserService userService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private GroupSendJobMapper groupSendJobMapper;
    @Autowired
    private UserExtInfoFeignService userExtInfoFeignService;
    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private WxworkUserMapper wxworkUserMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private HistoryDataFeignService historyDataFeignService;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private UzaiCashierServerFeignService uzaiCashierServerFeignService;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private TakeBalBlacklistMapper takeBalBlacklistMapper;
    @Autowired
    private RedPacketMapper redPacketMapper;
    @Autowired
    private MarketingRewardsBlackListService marketingRewardsBlackListService;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private MarketingRewardsService marketingRewardsService;
    @Autowired
    private MarketingTagMapper marketingTagMapper;
    @Autowired
    private AppUserMapper appUserMapper;

    @Autowired
    private RiskLevelMapper riskLevelMapper;

    /**
     * 分页查询微信用户列表
     *
     * @param wxpubUserQuery
     * @return null
     */
    @Override
    public Page<WxpubUserPageVo> findUserList(WxpubUserQuery wxpubUserQuery) {

        //返回到页面分页对象
        Page<WxpubUserPageVo> pageVo = new Page<>();

        //新建返回到页面的LIST对象
        List<WxpubUserPageVo> wxpubUserPageVoList = new ArrayList<WxpubUserPageVo>();

        //判断是否需要脱敏
        Boolean tuominFlag_mobile = true;
        String cmstype_user_mobile_verified =  (String)redisTemplate.opsForValue().get(String.format(Const.SmsType.CMSTYPE_USER_MOBILE, wxpubUserQuery.getMerId()));
        if(org.apache.commons.lang3.StringUtils.isNotBlank(cmstype_user_mobile_verified)){
            tuominFlag_mobile = false;
        }


        //执行分页查询对象
        Page<WxpubUser> page = new Page<>();
        wxpubUserQuery.convert(page);

        //判断是否有淘宝会员id条件
        if(org.apache.commons.lang3.StringUtils.isNotBlank(wxpubUserQuery.getSpecialId())){
            //清空其他条件
            WxpubUserQuery wxpubUserQuery_specialId = new WxpubUserQuery();
            wxpubUserQuery_specialId.setMerId(wxpubUserQuery.getMerId());
            wxpubUserQuery_specialId.setSize(wxpubUserQuery.getSize());
            wxpubUserQuery_specialId.setCurrent(wxpubUserQuery.getCurrent());
            wxpubUserQuery_specialId.setOrder(wxpubUserQuery.getOrder());
            wxpubUserQuery_specialId.setAsc(wxpubUserQuery.isAsc());
            wxpubUserQuery_specialId.setOrderByField(wxpubUserQuery.getOrderByField());
            wxpubUserQuery_specialId.setOrderItemList(wxpubUserQuery.getOrderItemList());
            wxpubUserQuery_specialId.setSpecialId(wxpubUserQuery.getSpecialId());
            //重新生成查询条件
            wxpubUserQuery = wxpubUserQuery_specialId;

            //查询淘宝会员信息
            TbUserInfoQuery tbUserInfoQuery = new TbUserInfoQuery();
            tbUserInfoQuery.setMerId(wxpubUserQuery.getMerId());
            tbUserInfoQuery.setSpecialId(wxpubUserQuery.getSpecialId());
            List<TbUserInfo> tbUserInfoList = tbUserInfoMapper.findByList(tbUserInfoQuery);
            if(tbUserInfoList != null && tbUserInfoList.size() > 0){
                List<Long> userIdList = new ArrayList<>();
                for (TbUserInfo tbUserInfo : tbUserInfoList) {
                    userIdList.add(tbUserInfo.getUserId());
                }
                wxpubUserQuery.setIdList(userIdList);
            }else{//未查询到淘宝会员id,则返回空
                return pageVo;
            }
        }

        // 判断是否带有风险条件id
        if (wxpubUserQuery.getRiskLevelId() != null) {
            RiskLevel riskLevel = riskLevelMapper.selectById(wxpubUserQuery.getRiskLevelId());
            if (riskLevel != null) {
                wxpubUserQuery.setMaxScore(riskLevel.getMaxScore());
                wxpubUserQuery.setMinScore(riskLevel.getMinScore());
            }
        }

        List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(page, wxpubUserQuery);

        if (wxpubUserList != null) {
            for (WxpubUser user : wxpubUserList) {
                WxpubUserPageVo wxpubUserPageVo = new WxpubUserPageVo();
                BeanUtils.copyProperties(user, wxpubUserPageVo);

                // 查询风险等级
//                if (user.getRiskScore() != null) {
//                    RiskLevel riskLevel = riskLevelMapper.selectByScore(user.getRiskScore());
//                    if (riskLevel != null) {
//                        wxpubUserPageVo.setRiskLevelName(riskLevel.getName());
//                    }
//
//                }

                //处理淘礼金脱敏显示
                //是否脱敏处理
                if(tuominFlag_mobile){
                    wxpubUserPageVo.setMobile(DesensitizeUtil.around(wxpubUserPageVo.getMobile(), 3, 4));
                }

                //身份名称
                wxpubUserPageVo.setIdentityName(IdentityEnum.getById(user.getIdentity()).getDesc());

                //会员类型名称
                if (user.getUserType() != null) {
                    UserType userType = userTypeMapper.selectById(user.getUserType(), wxpubUserQuery.getMerId());
                    if (userType != null) {
                        wxpubUserPageVo.setUserTypeName(userType.getName());
                    }
                }

                //上级用户
                if (user.getParentId() != null) {
                    if(user.getParentId().longValue() != 0){
                        WxpubUser wxpubUserParent = wxpubUserMapper.selectById(user.getParentId(), wxpubUserQuery.getMerId());
                        if (wxpubUserParent != null) {
                            wxpubUserPageVo.setParentName(wxpubUserParent.getNickName());
                        }
                    }else{
                        wxpubUserPageVo.setParentId(null);
                    }
                }

                //上级代理
                if (user.getAgentId() != null) {
                    if(user.getAgentId().longValue() != 0) {
                        WxpubUser wxpubUserAgent = wxpubUserMapper.selectById(user.getAgentId(), wxpubUserQuery.getMerId());
                        if (wxpubUserAgent != null) {
                            wxpubUserPageVo.setAgentName(wxpubUserAgent.getNickName());
                        }
                    }else{
                        wxpubUserPageVo.setAgentId(null);
                    }
                }

                //合伙人
                if (user.getPartnerId() != null) {
                    if(user.getPartnerId().longValue() != 0) {
                        WxpubUser wxpubUserAgent = wxpubUserMapper.selectById(user.getPartnerId(), wxpubUserQuery.getMerId());
                        if (wxpubUserAgent != null) {
                            wxpubUserPageVo.setPartnerName(wxpubUserAgent.getNickName());
                        }
                    }else{
                        wxpubUserPageVo.setPartnerId(null);
                    }

                }

                //查询机器人ID
                if (user.getDeviceUniqueId() != null) {
                    WxpubInfoEntity wxpubInfoEntity = wxpubInfoMapper.queryObject(user.getDeviceUniqueId());
                    if (wxpubInfoEntity != null) {
                        wxpubUserPageVo.setDeviceId(wxpubInfoEntity.getDeviceId());
                        wxpubUserPageVo.setDeviceName(wxpubInfoEntity.getDeviceName());
                        wxpubUserPageVo.setDeviceRemark(wxpubInfoEntity.getDeviceRemark());
                    }
                }

                //用户类型组信息
                if (user.getUserType() != null) {
                    UserType userType = userTypeMapper.selectById(user.getUserType(), wxpubUserQuery.getMerId());
                    if (userType != null) {
                        Long userTypeGroupId = userType.getGroupId();
                        if (userTypeGroupId != null) {
                            UserTypeGroup userTypeGroup = userTypeGroupMapper.selectById(userTypeGroupId, wxpubUserQuery.getMerId());
                            if (userTypeGroup != null) {
                                wxpubUserPageVo.setUserTypeGroupId(userTypeGroup.getId());
                                wxpubUserPageVo.setUserTypeGroupName(userTypeGroup.getName());
                            }
                        }
                    }
                }

                //标签List
                try {
                    wxpubUserPageVo.setTagsArr(JSONObject.parseArray(user.getTags(), String.class));
                }catch (Exception e){

                }

                //会员标签
                if(org.apache.commons.lang3.StringUtils.isNotBlank(user.getSysTags())){
                    try {
                        List<SysTagVo> sysTagVoList =  JSONObject.parseArray(user.getSysTags(), SysTagVo.class);
                        if(sysTagVoList != null && sysTagVoList.size() > 0){
                            List<SysTagShow> sysTagShowList = new ArrayList<>();
                            List<Long> sysTagsArr = new ArrayList<>();
                            for (SysTagVo sysTagVo : sysTagVoList) {
                                sysTagsArr.add(sysTagVo.getId());
                                SysTagShow sysTagShow = new SysTagShow();
                                BeanUtils.copyProperties(sysTagVo, sysTagShow);
                                //查询标签名称
                                MarketingTag marketingTag = marketingTagMapper.selectById(sysTagVo.getId(), wxpubUserQuery.getMerId());
                                if(marketingTag != null){
                                    sysTagShow.setName(marketingTag.getName());
                                }
                                sysTagShowList.add(sysTagShow);
                            }
                            wxpubUserPageVo.setSysTagsArr(sysTagsArr);
                            wxpubUserPageVo.setSysTagVoArr(sysTagShowList);
                        }
                    }catch (Exception e){ //如果不是JSON格式

                    }
                }


                UserExtInfoQueryDto userExtInfoQueryDto = new UserExtInfoQueryDto();
                userExtInfoQueryDto.setMerId(user.getMerId());
                userExtInfoQueryDto.setDeviceType(DeviceTypeEnum.WX_PUB.getId()); //个人用户
                userExtInfoQueryDto.setBizUserId(user.getBizUserId());
                List<String> keys = new ArrayList<>();
                keys.add("ValidOrderCount"); //首字母大写
                userExtInfoQueryDto.setKeys(keys);
                UzaiRespVo<EsUserExtInfo> uzaiRespVo = userExtInfoFeignService.getUserextinfo(userExtInfoQueryDto);
                logger.info("----订单总量----uzaiRespVo=" + JSONObject.toJSONString(uzaiRespVo));

                if (uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
                    EsUserExtInfo esUserExtInfo = uzaiRespVo.getData();
                    if (esUserExtInfo != null) {
                        wxpubUserPageVo.setOrderCount(esUserExtInfo.getValidOrderCount());
                    }
                }

                //是否在白名单当中
                String id_white = user.getMerId() + "_" + user.getBizUserId();
                Map<String,Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, id_white, null);
                if(white_map != null){
                    wxpubUserPageVo.setBlacklistFlag(3); //白名单
                    wxpubUserPageVo.setBlacklistId(user.getBizUserId());
                }

                //是否在全网黑名单当中
                String id_blacklistPub = user.getBizUserId();
                Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, id_blacklistPub, null);
                if(pub_map != null){
                    wxpubUserPageVo.setBlacklistFlag(2); //共享全网黑名单
                    wxpubUserPageVo.setBlacklistId(user.getBizUserId());
                }

                String id_blacklistPrv = user.getMerId() + "_" + user.getBizUserId();
                Map<String,Object> prv_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id_blacklistPrv, null);
                if(prv_map != null){ //在私有黑名单当中
                    wxpubUserPageVo.setBlacklistFlag(1); //私有黑名单
                    wxpubUserPageVo.setBlacklistId(id_blacklistPrv);
                }

                wxpubUserPageVoList.add(wxpubUserPageVo);
            }
        }

        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(wxpubUserPageVoList);
        //将返回对象排序(如果没有，则默认id排序降序)
        if(org.apache.commons.lang3.StringUtils.isBlank(wxpubUserQuery.getOrderByField()) &&  (wxpubUserQuery.getOrderItemList() == null || wxpubUserQuery.getOrderItemList().size() == 0)){
            Tools.sort(wxpubUserPageVoList, "id", wxpubUserQuery.isAsc()?"asc":"desc");
        }

        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 分页查询下级微信用户列表
     *
     * @param findSonWxpubUserListQuery
     * @return null
     */
    public Page<WxpubUserPageVo> findSonUserList(FindSonWxpubUserListQuery findSonWxpubUserListQuery){
        Long parentId = findSonWxpubUserListQuery.getParentId();
        if(parentId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入上级会员id");
        }

        Long merId = findSonWxpubUserListQuery.getMerId();
        if(merId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        Integer type = Tools.getInteger(findSonWxpubUserListQuery.getType());

        WxpubUser wxpubUser = wxpubUserMapper.selectById(parentId, merId);
        if(wxpubUser != null){
            if(Tools.getInteger(wxpubUser.getIdentity()).intValue() == IdentityEnum.BUYER.getId().intValue()){ //此会员是买家，则通过parentId来查询
                WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
                BeanUtils.copyProperties(findSonWxpubUserListQuery, wxpubUserQuery);
                wxpubUserQuery.setMerId(findSonWxpubUserListQuery.getMerId());
                wxpubUserQuery.setParentId(findSonWxpubUserListQuery.getParentId());
                wxpubUserQuery.setIdentity(IdentityEnum.BUYER.getId()); //只查买家
                return  findUserList(wxpubUserQuery);
            }else if(Tools.getInteger(wxpubUser.getIdentity()).intValue() == IdentityEnum.AGENT.getId().intValue()){
                if(type == 2){ //下级代理
                    WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
                    BeanUtils.copyProperties(findSonWxpubUserListQuery, wxpubUserQuery);
                    wxpubUserQuery.setParentId(null);
                    wxpubUserQuery.setMerId(findSonWxpubUserListQuery.getMerId());
                    wxpubUserQuery.setAgentId(findSonWxpubUserListQuery.getParentId());
                    wxpubUserQuery.setIdentity(IdentityEnum.AGENT.getId()); //只查代理
                    return  findUserList(wxpubUserQuery);
                }else if(type == 3 || type == 4){ //直推或者非直推买家
                    WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
                    BeanUtils.copyProperties(findSonWxpubUserListQuery, wxpubUserQuery);
                    wxpubUserQuery.setParentId(null);
                    wxpubUserQuery.setMerId(findSonWxpubUserListQuery.getMerId());
                    wxpubUserQuery.setAgentId(findSonWxpubUserListQuery.getParentId());
                    wxpubUserQuery.setIdentity(IdentityEnum.BUYER.getId()); //只查买家
                    if(type == 3){ //直推
                        wxpubUserQuery.setBuyerType(1);
                    }else{
                        wxpubUserQuery.setBuyerType(2); //非直推
                    }
                    return  findUserList(wxpubUserQuery);
                }
            }else{ //合伙人
                if(type == 1){ //买家
                    WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
                    BeanUtils.copyProperties(findSonWxpubUserListQuery, wxpubUserQuery);
                    wxpubUserQuery.setParentId(null);
                    wxpubUserQuery.setMerId(findSonWxpubUserListQuery.getMerId());
                    wxpubUserQuery.setPartnerId(findSonWxpubUserListQuery.getParentId());
                    wxpubUserQuery.setIdentity(IdentityEnum.BUYER.getId()); //只查买家
                    return  findUserList(wxpubUserQuery);
                }else if(type == 2){ //代理
                    WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
                    BeanUtils.copyProperties(findSonWxpubUserListQuery, wxpubUserQuery);
                    wxpubUserQuery.setParentId(null);
                    wxpubUserQuery.setMerId(findSonWxpubUserListQuery.getMerId());
                    wxpubUserQuery.setPartnerId(findSonWxpubUserListQuery.getParentId());
                    wxpubUserQuery.setIdentity(IdentityEnum.AGENT.getId()); //只查代理
                    return  findUserList(wxpubUserQuery);
                }
            }
        }

        //返回到页面分页对象
        Page<WxpubUserPageVo> pageVo = new Page<>();
        BeanUtils.copyProperties(findSonWxpubUserListQuery, pageVo);
        return pageVo;
    }


    @Override
    public WxpubUserInfoVo findUserInfo(WxpubUserIdDto wxpubUserIdDto) {


        if (wxpubUserIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //查询页面用户
        WxpubUser wxpubUser = wxpubUserMapper.selectById(wxpubUserIdDto.getId(), wxpubUserIdDto.getMerId());

        if (wxpubUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //返回给页面参数
        WxpubUserInfoVo wxpubUserInfoVo = new WxpubUserInfoVo();
        BeanUtils.copyProperties(wxpubUser, wxpubUserInfoVo);

        // 查询撸狗风险值
//        if (wxpubUser.getRiskScore() != null) {
//            RiskLevel riskLevel = riskLevelMapper.selectByScore(wxpubUser.getRiskScore());
//            if (riskLevel != null) {
//                wxpubUserInfoVo.setRiskLevelName(riskLevel.getName());
//            }
//        }

        //查询机器人ID
        if (wxpubUser.getDeviceUniqueId() != null) {
            WxpubInfoEntity wxpubInfoEntity = wxpubInfoMapper.queryObject(wxpubUser.getDeviceUniqueId());
            if (wxpubInfoEntity != null) {
                wxpubUserInfoVo.setDeviceId(wxpubInfoEntity.getDeviceId());
                wxpubUserInfoVo.setDeviceName(wxpubInfoEntity.getDeviceName());
                wxpubUserInfoVo.setDeviceRemark(wxpubInfoEntity.getDeviceRemark());
            }
        }

        //用户类型组信息
        if (wxpubUser.getUserType() != null) {
            UserType userType = userTypeMapper.selectById(wxpubUser.getUserType(), wxpubUserIdDto.getMerId());
            if (userType != null) {
                Long userTypeGroupId = userType.getGroupId();
                if (userTypeGroupId != null) {
                    UserTypeGroup userTypeGroup = userTypeGroupMapper.selectById(userTypeGroupId, wxpubUserIdDto.getMerId());
                    if (userTypeGroup != null) {
                        wxpubUserInfoVo.setUserTypeGroupId(userTypeGroup.getId());
                        wxpubUserInfoVo.setUserTypeGroupName(userTypeGroup.getName());
                    }
                }
            }
        }

        //标签
        try {
            wxpubUserInfoVo.setTagsArr(JSONObject.parseArray(wxpubUser.getTags(), String.class));
        }catch (Exception e){}

        //会员标签
        if(org.apache.commons.lang3.StringUtils.isNotBlank(wxpubUser.getSysTags())){
            try {
                List<SysTagVo> sysTagVoList =  JSONObject.parseArray(wxpubUser.getSysTags(), SysTagVo.class);
                if(sysTagVoList != null && sysTagVoList.size() > 0){
                    List<SysTagShow> sysTagShowList = new ArrayList<>();
                    List<Long> sysTagsArr = new ArrayList<>();
                    for (SysTagVo sysTagVo : sysTagVoList) {
                        sysTagsArr.add(sysTagVo.getId());
                        SysTagShow sysTagShow = new SysTagShow();
                        BeanUtils.copyProperties(sysTagVo, sysTagShow);
                        //查询标签名称
                        MarketingTag marketingTag = marketingTagMapper.selectById(sysTagVo.getId(), wxpubUser.getMerId());
                        if(marketingTag != null){
                            sysTagShow.setName(marketingTag.getName());
                        }
                        sysTagShowList.add(sysTagShow);
                    }
                    wxpubUserInfoVo.setSysTagsArr(sysTagsArr);
                    wxpubUserInfoVo.setSysTagVoArr(sysTagShowList);
                }
            }catch (Exception e){ //如果不是JSON格式

            }
        }


        //上级、代理、合伙人如果为0，变成null
        if (wxpubUserInfoVo.getParentId() != null && wxpubUserInfoVo.getParentId().longValue() == 0) {
            wxpubUserInfoVo.setParentId(null);
        }
        if (wxpubUserInfoVo.getAgentId() != null && wxpubUserInfoVo.getAgentId().longValue() == 0) {
            wxpubUserInfoVo.setAgentId(null);
        }
        if (wxpubUserInfoVo.getPartnerId() != null && wxpubUserInfoVo.getPartnerId().longValue() == 0) {
            wxpubUserInfoVo.setPartnerId(null);
        }

        //上级买家树
        if (StringUtils.isNotBlank(wxpubUserInfoVo.getParentInfo())) {
            String[] parentIdList = wxpubUserInfoVo.getParentInfo().split("_");
            if (parentIdList != null && parentIdList.length > 0) {
                List<UserTreeVo> parentInfoList = new ArrayList<>();
                for (String parentId : parentIdList) {
                    UserTreeVo userTreeVo = new UserTreeVo();
                    WxpubUser wxpubUser_parent = wxpubUserMapper.selectById(Long.valueOf(parentId), wxpubUserIdDto.getMerId());
                    if (wxpubUser_parent != null) {
                        userTreeVo.setId(wxpubUser_parent.getId());
                        userTreeVo.setNickName(wxpubUser_parent.getNickName());
                        parentInfoList.add(userTreeVo);
                    }
                }
                wxpubUserInfoVo.setParentInfoList(parentInfoList);
            }
        }

        //上级代理树
        if (StringUtils.isNotBlank(wxpubUserInfoVo.getAgentInfo())) {
            String[] agentIdList = wxpubUserInfoVo.getAgentInfo().split("_");
            if (agentIdList != null && agentIdList.length > 0) {
                List<UserTreeVo> agentInfoList = new ArrayList<>();
                for (String agentId : agentIdList) {
                    UserTreeVo userTreeVo = new UserTreeVo();
                    WxpubUser wxpubUser_agent = wxpubUserMapper.selectById(Long.valueOf(agentId), wxpubUserIdDto.getMerId());
                    if (wxpubUser_agent != null) {
                        userTreeVo.setId(wxpubUser_agent.getId());
                        userTreeVo.setNickName(wxpubUser_agent.getNickName());
                        agentInfoList.add(userTreeVo);
                    }
                }
                wxpubUserInfoVo.setAgentInfoList(agentInfoList);
            }
        }

        //是否在全网黑名单当中
        String id_blacklistPub = wxpubUser.getBizUserId();
        Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, id_blacklistPub, null);
        if(pub_map != null){
            wxpubUserInfoVo.setBlacklistFlag(2); //共享全网黑名单
            wxpubUserInfoVo.setBlacklistId(wxpubUser.getBizUserId());
        }

        //是否在白名单当中
        String id_white = wxpubUser.getMerId() + "_" + wxpubUser.getBizUserId();
        Map<String,Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, id_white, null);
        if(white_map != null){
            wxpubUserInfoVo.setBlacklistFlag(3); //白名单
            wxpubUserInfoVo.setBlacklistId(wxpubUser.getBizUserId());
        }

        String id_blacklistPrv = wxpubUser.getMerId() + "_" + wxpubUser.getBizUserId();
        Map<String,Object> prv_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id_blacklistPrv, null);
        if(prv_map != null){ //在私有黑名单当中
            wxpubUserInfoVo.setBlacklistFlag(1); //私有黑名单
            wxpubUserInfoVo.setBlacklistId(id_blacklistPrv);
        }


        //互通其他端会员信息
        if(StringUtils.isNotBlank(wxpubUser.getUzaiUnionId())){
            //个人微信会员互通信息
            WechatUser wechatUser = wechatUserMapper.selectByUzaiUnionId(wxpubUser.getUzaiUnionId(), wxpubUser.getMerId());
            if(wechatUser != null){
                wxpubUserInfoVo.setWechatUserId(wechatUser.getId());
            }

            //企业微信会员信息
            WxworkUser wxworkUser = wxworkUserMapper.selectByUzaiUnionId(wxpubUser.getUzaiUnionId(), wxpubUser.getMerId());
            if(wxworkUser != null){
                wxpubUserInfoVo.setWxworkUserId(wxworkUser.getId());
            }
        }

        try {
            //关联其他机器人
            List<DeviceInfoVo> deviceInfoVoList = new ArrayList<>();
            wxpubUserInfoVo.setDeviceInfoList(deviceInfoVoList);
            if(org.apache.commons.lang3.StringUtils.isNotBlank(wxpubUser.getDeviceInfos())){
                JSONObject deviceInfosObject  = JSONObject.parseObject(wxpubUser.getDeviceInfos());
                if(deviceInfosObject != null){
                    List<Long> deviceInfoList = new ArrayList<>();
                    Set<String> itName = deviceInfosObject.keySet();
                    if(itName != null && itName.size() > 0){
                        for (String key : itName) {
                            Long deviceUniqueId = deviceInfosObject.getLong(key);
                            Device device = deviceService.findDeviceInfoByDeviceUniqueId(deviceUniqueId, DeviceTypeEnum.WX_PUB.getKey(), wxpubUser.getMerId());
                            if(device != null){
                                DeviceInfoVo deviceInfoVo = new DeviceInfoVo();
                                BeanUtils.copyProperties(device, deviceInfoVo);
                                deviceInfoVoList.add(deviceInfoVo);
                            }

                        }
                    }
                }
            }
        }catch (Exception e){

        }

        try {
            //营销数据
            String uzai_marketing_reward_info = EsIndexName.UZAI_MARKETING_REWARD_INFO;
            String marketingRewardId = wxpubUser.getId() + "" + wxpubUser.getRegSource();
            Map<String, Object> dataMap = elasticsearchUtil.searchDataById(uzai_marketing_reward_info, marketingRewardId, null);
            MarketingRewardVo marketingRewardVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), MarketingRewardVo.class);
            if (marketingRewardVo == null) {
                marketingRewardVo = new MarketingRewardVo(true);
            }
            wxpubUserInfoVo.setMarketingReward(marketingRewardVo);

            String marketingRewardsBlackListId = marketingRewardsBlackListService.isInBlackList(wxpubUser.getBizUserId(), wxpubUser.getMerId());
            wxpubUserInfoVo.setMarketingRewardsBlackListId(marketingRewardsBlackListId);
        }catch (Exception e){

        }


        //淘宝SID,默认查询第一条
        TbUserInfoQuery tbUserInfoQuery = new TbUserInfoQuery();
        tbUserInfoQuery.setMerId(wxpubUser.getMerId());
        tbUserInfoQuery.setUserId(wxpubUser.getId());
        List<TbUserInfo> tbUserInfoList = tbUserInfoMapper.findByList(new Page<>(), tbUserInfoQuery);
        if(tbUserInfoList != null && tbUserInfoList.size() > 0){
            wxpubUserInfoVo.setSpecialId(tbUserInfoList.get(0).getSpecialId());
        }

        return wxpubUserInfoVo;
    }

    /**
     * 根据单个机器人群发消息
     *
     * @param wxpubUserBatchSendMsgDto
     * @return null
     */
    @Override
    @Async("taskExecutor")
    public void groupSendMsgByDeviceUniqueId(WxpubUserBatchSendMsgDto wxpubUserBatchSendMsgDto) {
        WxpubUserQuery wxpubUserQuery = wxpubUserBatchSendMsgDto.getWxpubUserQuery();
        GroupSendJob groupSendJobParent = wxpubUserBatchSendMsgDto.getGroupSendJobParent();
        if (wxpubUserQuery == null) {//判断条件是否为空
            logger.error("--groupSendMsgByDeviceUniqueId is error; wxpubUserQuery is null");
            return;
        }
        if (wxpubUserQuery.getDeviceUniqueId() == null) {//判断机器人是否为空
            logger.error("--groupSendMsgByDeviceUniqueId is error; deviceUniqueId is null");
            return;
        }

        if (groupSendJobParent == null) {
            logger.error("--groupSendMsgByDeviceUniqueId is error; groupSendJobParent is null");
            return;
        }
        WxpubInfoEntity wxpubInfoEntity = wxpubInfoMapper.queryObject(wxpubUserQuery.getDeviceUniqueId());
        if (wxpubInfoEntity == null) {
            logger.error("--groupSendMsgByDeviceUniqueId is error; wxpubInfoEntity is null,  deviceUniqueId={}" + wxpubUserQuery.getDeviceUniqueId());
            return;
        }

        //GroupSendJob groupSendJob = groupSendJobMapper.selectById(wxpubUserBatchSendMsgDto.getParentId());
//        if(groupSendJob == null){
//            logger.error("--groupSendMsgByDeviceUniqueId is error; parentTGroupSendJob is null(群发消息主任务不存在) ");
//            return;
//        }

        //查询这个机器人的所有会员
        Page<WxpubUser> page = new Page<>();
        wxpubUserQuery.convert(page);
        List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(page, wxpubUserQuery);
        if (wxpubUserList != null && wxpubUserList.size() > 0) {
            Integer now = DateUtil.getNowTime();
            //添加群发消息子任务
            GroupSendJob groupSendJob_son = new GroupSendJob();
            groupSendJob_son.setId(IdWorker.getId());
            groupSendJob_son.setParentId(groupSendJobParent.getId()); //主任务id
            groupSendJob_son.setMerId(wxpubUserBatchSendMsgDto.getMerId());
            groupSendJob_son.setDeviceType(DeviceTypeEnum.WX_PUB.getKey());
            groupSendJob_son.setDeviceUniqueId(wxpubUserQuery.getDeviceUniqueId());
            groupSendJob_son.setName(groupSendJobParent.getName());
            groupSendJob_son.setSource(GroupSendJobSourceEnum.PRIVATE_USER.getId());
            groupSendJob_son.setContent(groupSendJobParent.getContent());
            groupSendJob_son.setStatus(GroupSendStatusEnum.NOT_START.getValue());
            groupSendJob_son.setTotalCount((int) page.getTotal());
            groupSendJob_son.setFinishCount(0);
            groupSendJob_son.setTimeInterval(groupSendJobParent.getTimeInterval());
            groupSendJob_son.setBeginTime(groupSendJobParent.getBeginTime());
            groupSendJob_son.setExptime(groupSendJobParent.getExptime()); //当前时间之后的15天内
            groupSendJob_son.setUserLab(groupSendJobParent.getUserLab());
            groupSendJob_son.setUserRemark(groupSendJobParent.getUserRemark());
            groupSendJob_son.setNightTime(groupSendJobParent.getNightTime());
            groupSendJob_son.setCreateTime(now);
            groupSendJob_son.setUpdateTime(now);
            groupSendJobMapper.insertSelective(groupSendJob_son);

            try {
                //线程睡眠0.5秒
                Thread.sleep(500);
            } catch (Exception e) {

            }

            //延迟时间
            int delay = 0;//循环累加延迟时间
            while (wxpubUserList != null && wxpubUserList.size() > 0) {
                //发送消息
                for (WxpubUser wxpubUser : wxpubUserList) {
                    //发送MQ消息
                    GroupSendMsgDto groupSendMsgDto = new GroupSendMsgDto();
                    groupSendMsgDto.setParentJobId(groupSendJob_son.getParentId());
                    groupSendMsgDto.setChildJobId(groupSendJob_son.getId());
                    String msg = Tools.getStr(groupSendJob_son.getContent());
                    groupSendMsgDto.setMsg(msg.replace("[昵称]", wxpubUser.getNickName()));
                    groupSendMsgDto.setMerId(wxpubUser.getMerId());
                    groupSendMsgDto.setDeviceUniqueId(wxpubUser.getDeviceUniqueId());
                    groupSendMsgDto.setDeviceType(DeviceTypeEnum.WX_PUB_VALUE);
                    groupSendMsgDto.setMsgType(MessageTypeEnum.MT_TEXT.getValue());
                    groupSendMsgDto.setUserId(wxpubUser.getId());
                    groupSendMsgDto.setBizUserId(wxpubUser.getBizUserId());
                    groupSendMsgDto.setNickName(wxpubUser.getNickName());
                    groupSendMsgDto.setDelay(delay);
                    groupSendMsgDto.setOriginalDelay(delay);
                    delay = delay + groupSendJobParent.getTimeInterval(); //循环累加延迟时间
                    groupSendMsgDto.setRetry(0);
                    groupSendMsgDto.setLabel(groupSendJobParent.getUserLab());
                    String remark = Tools.getStr(groupSendJobParent.getUserRemark()).replace("[昵称]", wxpubUser.getNickName());
                    groupSendMsgDto.setRemark(remark);
                    //群发消息
                    noticeMsgPushProducerService.groupSendMsg(groupSendMsgDto);
                }
                page.setCurrent(page.getCurrent() + 1); //页码+1
                wxpubUserList = wxpubUserMapper.findByList(page, wxpubUserQuery);
            }
        }
    }

    /**
     * 删除所有查询的会员数据
     *
     * @param wxpubUserBatchDeleteDto
     * @return null
     */
    @Override
    public void deleteUserSelected(WxpubUserBatchDeleteDto wxpubUserBatchDeleteDto) {

        Long merId = wxpubUserBatchDeleteDto.getMerId();
        Merchant merchant = merchantService.findByMerId(merId);
        if(merchant == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        //查询运营商短信验证功能信息
        boolean smsCodeFlag = true;
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.SMS_CODE_CONFIG.getValue());
        if (merBaseConfig != null) {
            SmsCodeVo smsCodeVo = JSONObject.parseObject(merBaseConfig.getVal(), SmsCodeVo.class);
            if(smsCodeVo != null && smsCodeVo.getWxpubUserDelByQuery() == 0){ //不需要认证
                smsCodeFlag = false;
            }
        }

        if(smsCodeFlag){
            //如果输入的验证码不是系统通用密码，则需要验证
            if(!uzaiConsoleSysConfig.getDefaultPassword().equals(wxpubUserBatchDeleteDto.getCode())){
                //获取存在redis中的验证码
                String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
                //判断验证码是否过期
                if (org.apache.commons.lang3.StringUtils.isBlank(codeByRedis)){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                }
                //验证码是否正确
                if (!codeByRedis.equals(wxpubUserBatchDeleteDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(wxpubUserBatchDeleteDto.getCode())){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                }
                //验证成功，删除验证码
                redisTemplate.delete(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
            }
        }

        WxpubUserQuery wxpubUserQuery = wxpubUserBatchDeleteDto.getWxpubUserQuery();
        wxpubUserQuery.setMerId(wxpubUserBatchDeleteDto.getMerId());
        //查询总数
        Integer count = wxpubUserMapper.findCount(wxpubUserQuery);
        //每页个数
        int size = 10;
        if(Tools.getInteger(count) > 0 ){
            int totalPage = count / size + 1; //总页数
            for(int i = totalPage ; i>0;  i--){
                //每个时间段分页查询，每页200个
                Page<WxpubUser> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(page, wxpubUserQuery);
                if(wxpubUserList != null && wxpubUserList.size() > 0){
                    for(WxpubUser wxpubUser : wxpubUserList) {
                        try{
                            deleteUserById(wxpubUser.getId(), wxpubUserQuery.getMerId());
                        }catch (Exception e){
                            logger.error("-------deleteUserById is error userId={}, error={}", wxpubUser.getId(), e.getMessage());
                        }
                    }
                }
            }
        }

//        //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
//        MinMaxCreateTimeVo minMaxCreateTimeVo = wxpubUserMapper.findMinAndMaxCreateTime(wxpubUserQuery);
//        //查询总数
//        Integer count = wxpubUserMapper.findCount(wxpubUserQuery);
//        //有总数，且最小创建时间有
//        if(minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
//            //则循环查询10天内的创建的会员
//            int duration = 5 * 24 * 3600;
//            List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
//            if (timeVOList != null && timeVOList.size() > 0) {
//                for (TimeVO timeVO : timeVOList) {
//                    wxpubUserQuery.setCreateTimeStart(timeVO.getBeginTime());
//                    wxpubUserQuery.setCreateTimeEnd(timeVO.getEndTime());
//
//                    //每个时间段分页查询，每页200个
//                    Page<WxpubUser> page = new Page<>();
//                    int current = 1;
//                    page.setCurrent(current);
//                    page.setSize(10);//最大支持10，如果此时间段数据大于10，则分页查询
//
//                    List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(page, wxpubUserQuery);
//                    while (wxpubUserList != null && wxpubUserList.size() > 0) {
//                        for (WxpubUser wxpubUser : wxpubUserList) {
//                            deleteUserById(wxpubUser.getId(), wxpubUserQuery.getMerId());
//                        }
//                        wxpubUserList = wxpubUserMapper.findByList(page, wxpubUserQuery);
//                    }
//
//                }
//            }
//        }
    }

    /**
     * 删除用户信息
     *
     * @param id
     * @return null
     */
    @Override
    public void deleteUserById(Long id, Long merId) {
        WxpubUser wxpubUser = wxpubUserMapper.selectById(id, merId);
        if (wxpubUser == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "用户不存在");
        }

        //判断是否关联APP，如果关联，不允许删除
        int appUserCount = appUserMapper.countByRelUserId(wxpubUser.getId());
        if(appUserCount > 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "此会员关联app，不能删除");
        }

        //真删除
        wxpubUserMapper.deleteById(id, merId);

        //删除缓存
        redisTemplate.delete(String.format(RedisCacheKeyEnum.WXPUB_USER_ID.getKey(), merId, wxpubUser.getBizUserId()));


        //删除ES
        try {
            //删除会员基本信息
            String uzai_user_info_id = DeviceTypeEnum.WX_PUB.getKey() + "_" + wxpubUser.getMerId() + "_" + wxpubUser.getBizUserId();
            String uzai_user_info = merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_INFO, wxpubUser.getMerId());
            elasticsearchUtil.deleteDataById(uzai_user_info, uzai_user_info_id);

            //删除会员扩展信息
            String uzai_user_ext_info_id = DeviceTypeEnum.WX_PUB.getKey() + "_" + wxpubUser.getMerId() + "_" + wxpubUser.getBizUserId();
            String uzai_user_ext_info = merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wxpubUser.getMerId());
            elasticsearchUtil.deleteDataById(uzai_user_ext_info, uzai_user_ext_info_id);

            //删除营销奖励信息
            String uzai_user_marketing_reward_info_id = wxpubUser.getId() + "" + wxpubUser.getRegSource();
            elasticsearchUtil.deleteDataById(EsIndexName.UZAI_MARKETING_REWARD_INFO, uzai_user_marketing_reward_info_id);

        } catch (Exception e) {
            logger.error("删除ES会员扩展信息出现异常:{}" + e.getMessage());
        }

        //根据此会员的身份来查询下级用户
        if (wxpubUser.getIdentity().intValue() == IdentityEnum.BUYER.getId()) { //此会员是买家
            //查询所有下级买家
            WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
            wxpubUserQuery.setMerId(wxpubUser.getMerId());
            wxpubUserQuery.setParentId(wxpubUser.getId());
            List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(wxpubUserQuery);
            if (wxpubUserList != null && wxpubUserList.size() > 0) {
                for (WxpubUser wxpubUser_son : wxpubUserList) {

                    //旧上级树
                    String parentInfoOld_Nson = wxpubUser_son.getParentInfo();

                    //将此会员的上级清空
                    wxpubUser_son.setParentId(0L);
                    wxpubUser_son.setParentInfo("");
                    wxpubUser_son.setUpdateTime(DateUtil.getNowTime());
                    wxpubUserMapper.updateIdentityInfo(wxpubUser_son);

                    //批量替换清空
                    wxpubUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "", wxpubUser.getMerId(), true);
                    wxpubUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, "", wxpubUser.getMerId(), false);

                }
            }
        } else if (wxpubUser.getIdentity().intValue() == IdentityEnum.AGENT.getId()) {//代理身份
            //查询所有下级代理
            WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
            wxpubUserQuery.setMerId(wxpubUser.getMerId());
            wxpubUserQuery.setAgentId(wxpubUser.getId());
            List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(wxpubUserQuery);
            if (wxpubUserList != null && wxpubUserList.size() > 0) {
                for (WxpubUser wxpubUser_son : wxpubUserList) {

                    //旧代理树
                    String agentInfoOld_Nson = wxpubUser_son.getAgentInfo();

                    //将此会员的代理信息给下级代理
                    wxpubUser_son.setAgentId(0L);
                    wxpubUser_son.setAgentInfo("");
                    wxpubUser_son.setUpdateTime(DateUtil.getNowTime());
                    wxpubUserMapper.updateIdentityInfo(wxpubUser_son);

                    //批量替换
                    wxpubUserMapper.batchUpdateParentInfo("_" + agentInfoOld_Nson, "", wxpubUser.getMerId(), true);
                    wxpubUserMapper.batchUpdateParentInfo(agentInfoOld_Nson, "", wxpubUser.getMerId(), false);
                }
            }
        } else if (wxpubUser.getIdentity().intValue() == IdentityEnum.AGENT.getId()) {//合伙人身份
            //查询所有下级代理
            WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
            wxpubUserQuery.setMerId(wxpubUser.getMerId());
            wxpubUserQuery.setPartnerId(wxpubUser.getId());
            List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(wxpubUserQuery);
            if (wxpubUserList != null && wxpubUserList.size() > 0) {
                for (WxpubUser wxpubUser_son : wxpubUserList) {
                    wxpubUser_son.setPartnerId(0L); //清空合伙人
                    wxpubUser_son.setUpdateTime(DateUtil.getNowTime());
                    wxpubUserMapper.updateIdentityInfo(wxpubUser_son);
                }
            }
        }

    }

    /**
     * 删除上下级会员关系
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxpubUserDeleteSonDto
     * @return null
     */
    public void deleteSonWxpubUser(WxpubUserDeleteSonDto wxpubUserDeleteSonDto){

        Long merId = wxpubUserDeleteSonDto.getMerId();
        Long id = wxpubUserDeleteSonDto.getId();
        Integer identity = wxpubUserDeleteSonDto.getIdentity();

        if(identity == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "身份参数不能为空");
        }

        WxpubUser wxpubUser = wxpubUserMapper.selectById(id, merId);
        if(wxpubUser == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "用户不存在");
        }

        //上级会员
        WxpubUser wxpubUserParent = null;

        //根据此会员的身份来查询下级用户
        if(identity.intValue() == IdentityEnum.BUYER.getId().intValue()){ //此会员是买家
            Long parentId = wxpubUser.getParentId();
            wxpubUserParent = wxpubUserMapper.selectById(parentId, merId);
            //清理上级买家关系
            wxpubUser.setParentId(0L);
            wxpubUser.setParentInfo("");
            wxpubUser.setUpdateTime(DateUtil.getNowTime());
            wxpubUserMapper.updateIdentityInfo(wxpubUser);

            //查询所有下级买家
            WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
            wxpubUserQuery.setMerId(wxpubUser.getMerId());
            wxpubUserQuery.setParentId(wxpubUser.getId());

            //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
            MinMaxCreateTimeVo minMaxCreateTimeVo = wxpubUserMapper.findMinAndMaxCreateTime(wxpubUserQuery);
            //查询总数
            Integer count = wxpubUserMapper.findCount(wxpubUserQuery);
            //有总数，且最小创建时间有
            if(minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                //则循环查询5天内的创建的会员
                int duration = 5 * 24 * 3600;
                List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                if (timeVOList != null && timeVOList.size() > 0) {
                    for (TimeVO timeVO : timeVOList) {
                        wxpubUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                        wxpubUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                        List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(wxpubUserQuery);
                        if(wxpubUserList != null && wxpubUserList.size() > 0){
                            for (WxpubUser wxpubUser_son : wxpubUserList){
                                //旧上级树
                                String parentInfoOld_Nson = wxpubUser_son.getParentInfo();
                                //将此会员的上级树修改为上级的id
                                wxpubUser_son.setParentInfo(String.valueOf(wxpubUser.getId()));
                                wxpubUser_son.setUpdateTime(DateUtil.getNowTime());
                                wxpubUserMapper.updateIdentityInfo(wxpubUser_son);
                                //批量替换清空
                                wxpubUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, String.valueOf(wxpubUser.getId()), wxpubUser.getMerId(), false);
                            }
                        }
                    }
                }
            }
        }else if(identity.intValue() == IdentityEnum.AGENT.getId().intValue()){//代理身份

            Long agentId = wxpubUser.getAgentId();
            wxpubUserParent = wxpubUserMapper.selectById(agentId, merId);

            //清理上级代理关系
            wxpubUser.setAgentId(0L);
            wxpubUser.setAgentInfo("");
            wxpubUser.setUpdateTime(DateUtil.getNowTime());
            wxpubUserMapper.updateIdentityInfo(wxpubUser);

            //查询所有下级代理
            WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
            wxpubUserQuery.setMerId(wxpubUser.getMerId());
            wxpubUserQuery.setAgentId(wxpubUser.getId());

            //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
            MinMaxCreateTimeVo minMaxCreateTimeVo = wxpubUserMapper.findMinAndMaxCreateTime(wxpubUserQuery);
            //查询总数
            Integer count = wxpubUserMapper.findCount(wxpubUserQuery);
            //有总数，且最小创建时间有
            if(minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                //则循环查询5天内的创建的会员
                int duration = 5 * 24 * 3600;
                List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                if (timeVOList != null && timeVOList.size() > 0) {
                    for (TimeVO timeVO : timeVOList) {
                        wxpubUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                        wxpubUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                        List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(wxpubUserQuery);
                        if(wxpubUserList != null && wxpubUserList.size() > 0){
                            for (WxpubUser wxpubUser_son : wxpubUserList){
                                //旧代理树
                                String agentInfoOld_Nson = wxpubUser_son.getAgentInfo();
                                //将此会员的代理信息给下级代理
                                wxpubUser_son.setAgentInfo(String.valueOf(wxpubUser.getId()));
                                wxpubUser_son.setUpdateTime(DateUtil.getNowTime());
                                wxpubUserMapper.updateIdentityInfo(wxpubUser_son);
                                //批量替换
                                wxpubUserMapper.batchUpdateParentInfo(agentInfoOld_Nson, String.valueOf(wxpubUser.getId()), wxpubUser.getMerId(), false);
                            }
                        }
                    }
                }
            }
        }else if(identity.intValue() == IdentityEnum.PARTNER.getId().intValue()){//合伙人

            Long partnerId = wxpubUser.getPartnerId();
            wxpubUserParent = wxpubUserMapper.selectById(partnerId, merId);

            //清理合伙人关系
            wxpubUser.setPartnerId(0L);
            wxpubUser.setUpdateTime(DateUtil.getNowTime());
            wxpubUserMapper.updateIdentityInfo(wxpubUser);
        }

        //修改ES
        try{
            //修改会员扩展信息
            String uzai_user_ext_info_id = DeviceTypeEnum.WX_PUB.getKey() + "_" + wxpubUser.getMerId() + "_" + wxpubUser.getBizUserId();
            //查询会员基本信息
            Map<String,Object> dataMp_ext = elasticsearchUtil.searchDataById(merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wxpubUser.getMerId()), uzai_user_ext_info_id, null);
            if(dataMp_ext != null){
                EsUserExtInfo esUserExtInfo = new EsUserExtInfo();
                BeanUtils.copyProperties(wxpubUser, esUserExtInfo);
                esUserExtInfo.setId(uzai_user_ext_info_id);
                elasticsearchUtil.updateDataById(esUserExtInfo, merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wxpubUser.getMerId()), uzai_user_ext_info_id);
            }

        }catch (Exception e){
            logger.error("修改会员营销策略信息出现异常:{}"+ e.getMessage());
        }


        //断绝下级关系，发送修改会员敏感信息报警消息
        AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
        alarmMsgFeignDto.setMerId(wxpubUserDeleteSonDto.getMerId());
        alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER.getValue()); //修改会员敏感信息
        //消息
        JSONObject ext = new JSONObject();
        //当前操作员
        String token_key = String.format(CacheKey.LOGIN_TOKEN, wxpubUserDeleteSonDto.getLoginToken());
        Object data = redisTemplate.opsForValue().get(token_key);
        LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
        //发送修改会员数据提醒通知
        if(wxpubUserParent == null){
            wxpubUserParent = new WxpubUser();
        }
        StringBuffer content = new StringBuffer("正在删除会员的下级：")
                .append(wxpubUser.getNickName())
                .append("(").append(wxpubUser.getWxid()).append(")");

        ext.put("childuser", loginVo.getLoginName());
        ext.put("content", content);
        ext.put("nick", wxpubUserParent.getNickName());
        ext.put("wxid", wxpubUserParent.getBizUserId());
        ext.put("userid", wxpubUserParent.getId());
        ext.put("phone", loginVo.getMobile());
        alarmMsgFeignDto.setExt(ext.toJSONString());
//        UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//        logger.info("---发送删除下级会员关系报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

        //2024-01-09修改成直接发送MQ
        noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
    }

    /**
     * 分页查询微信用户账户明细列表
     *
     * @param userAccDetailQuery
     * @return null
     */
    public Page<UserAccDetailInfoVo> findWxpubUserAccDetailList(UserAccDetailQuery userAccDetailQuery) {

        //用户ID不能为空，必须指定用户
        if (userAccDetailQuery.getUserId() == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请指定用户进行查询");
        }

        //新建返回到页面的LIST对象
        List<UserAccDetailInfoVo> wxpubUserAccDetailInfoVoList = new ArrayList<UserAccDetailInfoVo>();
        //执行分页查询对象
        Page<UserAccDetail> page = new Page<>();
        userAccDetailQuery.convert(page);
        List<UserAccDetail> wxpubUserList = userAccDetailMapper.findByList(page, userAccDetailQuery);
        if (wxpubUserList != null) {
            for (UserAccDetail userAccDetail : wxpubUserList) {
                UserAccDetailInfoVo userAccDetailInfoVo = new UserAccDetailInfoVo();
                BeanUtils.copyProperties(userAccDetail, userAccDetailInfoVo);
                //用户昵称
                WxpubUser wxpubUser = wxpubUserMapper.selectById(userAccDetail.getUserId(), userAccDetailQuery.getMerId());
                if (wxpubUser != null) {
                    userAccDetailInfoVo.setNickName(wxpubUser.getNickName());
                }
                //明细类型
                userAccDetailInfoVo.setTypeName(AccDetailTypeEnum.getById(userAccDetail.getType()).getDesc());

                //订单编号商户订单号
                userAccDetailInfoVo.setOrderIdTradeno(Tools.getStr(userAccDetail.getOrderId()) + Tools.getStr(userAccDetail.getTradeno()));
                wxpubUserAccDetailInfoVoList.add(userAccDetailInfoVo);
            }
        }
        //返回到页面分页对象
        Page<UserAccDetailInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(wxpubUserAccDetailInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }


    /**
     * 分页查询微信公众号用户账户明细列表
     *
     * @param userAccDetailQuery
     * @return null
     */
    @Override
    public Page<UserAccDetailInfoVo> findUserAccDetailList(UserAccDetailQuery userAccDetailQuery) {

        //用户ID不能为空，必须指定用户
        if (userAccDetailQuery.getUserId() == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请指定用户进行查询");
        }

        //新建返回到页面的LIST对象
        List<UserAccDetailInfoVo> wxpubUserAccDetailInfoVoList = new ArrayList<UserAccDetailInfoVo>();
        //执行分页查询对象
        Page<UserAccDetail> page = new Page<>();
        userAccDetailQuery.convert(page);

        List<UserAccDetail> userAccDetailList = null;
        if (super.checkStartEndTimeIsHistoryQuery(userAccDetailQuery.getQueryStartTime(), userAccDetailQuery.getQueryEndTime(), userAccDetailQuery.getQueryMonth())) {
            String tableSuffix = DateTime.of(userAccDetailQuery.getQueryEndTime() * 1000L).toString("yyMM");
            UzaiRespVo<Page<UserAccDetail>> listUzaiRespVoRes = historyDataFeignService.searchAccDetail(tableSuffix, userAccDetailQuery);
            if (listUzaiRespVoRes.getCode() != 200) {
                throw new BusinessException("提现列表查询失败");
            }

            if(listUzaiRespVoRes.getData() != null){
                userAccDetailList = listUzaiRespVoRes.getData().getRecords();
                page.setTotal(listUzaiRespVoRes.getData().getTotal());
            }

        }else{// 反之查询90天内的订单数据
            userAccDetailList = userAccDetailMapper.findByList(page, userAccDetailQuery);
        }

        if (userAccDetailList != null) {
            for (UserAccDetail wxpubUserAccDetail : userAccDetailList) {
                UserAccDetailInfoVo wxpubUserAccDetailInfoVo = new UserAccDetailInfoVo();
                BeanUtils.copyProperties(wxpubUserAccDetail, wxpubUserAccDetailInfoVo);
                //用户昵称
                WxpubUser wxpubUser = wxpubUserMapper.selectById(wxpubUserAccDetail.getUserId(), userAccDetailQuery.getMerId());
                if (wxpubUser != null) {
                    wxpubUserAccDetailInfoVo.setNickName(wxpubUser.getNickName());
                }
                //明细类型
                wxpubUserAccDetailInfoVo.setTypeName(AccDetailTypeEnum.getById(wxpubUserAccDetail.getType()).getDesc());

                //订单编号商户订单号
                wxpubUserAccDetailInfoVo.setOrderIdTradeno(Tools.getStr(wxpubUserAccDetail.getOrderId()) + "/" + Tools.getStr(wxpubUserAccDetail.getTradeno()));
                wxpubUserAccDetailInfoVoList.add(wxpubUserAccDetailInfoVo);
            }
        }
        //返回到页面分页对象
        Page<UserAccDetailInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(wxpubUserAccDetailInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 分页查询用户会员渠道ID列表
     *
     * @param tbUserInfoQuery
     * @return null
     */
    @Override
    public Page<TbUserInfoVo> findTbUserInfoList(TbUserInfoQuery tbUserInfoQuery) {
        //新建返回到页面的LIST对象
        List<TbUserInfoVo> tbUserInfoVoList = new ArrayList<TbUserInfoVo>();
        //执行分页查询对象
        Page<TbUserInfo> page = new Page<>();
        tbUserInfoQuery.convert(page);
        List<TbUserInfo> tbUserInfoList = tbUserInfoMapper.findByList(page, tbUserInfoQuery);
        if (tbUserInfoList != null) {
            for (TbUserInfo tbUserInfo : tbUserInfoList) {
                TbUserInfoVo tbUserInfoVo = new TbUserInfoVo();
                BeanUtils.copyProperties(tbUserInfo, tbUserInfoVo);
                //用户昵称
                TbToken tbToken = tbTokenMapper.selectByUserIdAndTurnLink(tbUserInfo.getTbTokenId(),0);
                if(tbToken == null){
                    tbToken = tbTokenMapper.selectByUserIdAndTurnLink(tbUserInfo.getTbTokenId(), 1);
                }
                if (tbToken != null) {
                    tbUserInfoVo.setTbTokenName(tbToken.getUserName());
                }
                tbUserInfoVoList.add(tbUserInfoVo);
            }
        }
        //返回到页面分页对象
        Page<TbUserInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(tbUserInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 修改会员渠道ID
     *
     * @param tbUserInfoUpdateDto
     * @return null
     */
    @Override
    public void updateTbUserInfo(TbUserInfoUpdateDto tbUserInfoUpdateDto) {
        if (tbUserInfoUpdateDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        TbUserInfo tbUserInfo = tbUserInfoMapper.selectById(tbUserInfoUpdateDto.getId(), tbUserInfoUpdateDto.getMerId());
        tbUserInfo.setSpecialId(tbUserInfoUpdateDto.getSpecialId());
        tbUserInfo.setRelationId(tbUserInfoUpdateDto.getRelationId());
        tbUserInfo.setUpdateTime(DateUtil.getNowTime());
        tbUserInfoMapper.updateById(tbUserInfo);
    }

    /**
     * 删除会员渠道ID
     *
     * @param tbUserInfoIdDto
     * @return null
     */
    @Override
    public void deleteTbUserInfo(TbUserInfoIdDto tbUserInfoIdDto) {
        if (tbUserInfoIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        tbUserInfoMapper.deleteById(tbUserInfoIdDto.getId(), tbUserInfoIdDto.getMerId());
    }


    /**
     * 修改微信用户积分余额
     *
     * @param wxpubUserUpdateBalanceDto
     * @return null
     */
    @Override
    @Transactional
    public void updateWxpubUserBalance(WxpubUserUpdateBalanceDto wxpubUserUpdateBalanceDto) {

        if(wxpubUserUpdateBalanceDto.getId() == null || wxpubUserUpdateBalanceDto.getBalance() ==null || wxpubUserUpdateBalanceDto.getIntegral() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //至少要修改一个
        if(wxpubUserUpdateBalanceDto.getBalance() == null && wxpubUserUpdateBalanceDto.getIntegral() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "积分和余额至少要修改一项");
        }

        //修改值不能为负数
        if(Tools.getDouble(wxpubUserUpdateBalanceDto.getBalance()).doubleValue() <  0 || Tools.getInteger(wxpubUserUpdateBalanceDto.getIntegral()).intValue() < 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只能输入大于0的数");
        }

        if(org.apache.commons.lang3.StringUtils.isNotBlank(wxpubUserUpdateBalanceDto.getRemark())){
            //判断是否包括表情
            if(EmojiUtil.containsEmoji(wxpubUserUpdateBalanceDto.getRemark())){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "原因不能包含表情符号");
            }
        }

        WxpubUser wxpubUser = wxpubUserMapper.selectById(wxpubUserUpdateBalanceDto.getId(), wxpubUserUpdateBalanceDto.getMerId());
        if(wxpubUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //发送修改会员数据提醒通知
        StringBuffer content = new StringBuffer("正在修改会员余额和积分;");
        //AOP切面，封装操作日志内容
        String aspectOperatorLog = "修改余额积分";
        //变更余额
        Double balance = wxpubUserUpdateBalanceDto.getBalance();
        Double changeBalance = 0.0D;
        //表示修改余额
        if(balance != null){
            //修改类型类型
            Integer balanceType = wxpubUserUpdateBalanceDto.getBalanceType();
            if(balanceType == null){ //修改余额
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入余额修改类型");
            }
            if(!Lists.newArrayList(-1,0,1).contains(balanceType)){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "余额修改类型值有误");
            }

            //旧余额
            Double oldBalance = Tools.getDouble(wxpubUser.getBalance());
            //新余额
            Double newBalance = 0.00D;
            if(balanceType.intValue() == -1){ //减量
                //减少
                newBalance = Math.sub(oldBalance, balance);
                changeBalance = Math.sub(0, balance);
                aspectOperatorLog = aspectOperatorLog + "；减少余额:" + balance;
            }else if(balanceType.intValue() == 1){ //增量
                //增加
                newBalance = Math.add(oldBalance, balance);
                changeBalance = balance;
                aspectOperatorLog = aspectOperatorLog + "；增加余额:" + balance;
            }else{//修改成指定值
                newBalance = balance;
                changeBalance = Math.sub(newBalance, oldBalance);
                aspectOperatorLog = aspectOperatorLog + "；修改余额:" + balance;
            }
            wxpubUser.setBalance(newBalance);

            content.append("变动余额:" + changeBalance).append(";");
        }


        //表示修改积分
        Integer integral = wxpubUserUpdateBalanceDto.getIntegral();
        //变更积分
        Integer changeIntegral = 0;
        if(integral != null) {
            //修改积分类型
            Integer integralType = wxpubUserUpdateBalanceDto.getIntegralType();
            if(integralType == null){ //修改积分
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入积分修改类型");
            }
            if(!Lists.newArrayList(-1,0,1).contains(integralType)){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "积分修改类型值有误");
            }

            //旧积分
            Integer oldIntegral = Tools.getInteger(wxpubUser.getIntegral());
            //新积分
            Integer newIntegral = 0;

            if(integralType.intValue() == -1){ //减量
                //减少
                newIntegral = oldIntegral - integral;
                changeIntegral = 0 - integral;
                aspectOperatorLog = aspectOperatorLog + "；减少积分:" + integral;
            }else if(integralType.intValue() == 1){ //增量
                //增加
                newIntegral = oldIntegral + integral;
                changeIntegral = integral;
                aspectOperatorLog = aspectOperatorLog + "；增加积分:" + integral;
            }else{//修改成指定值
                newIntegral = integral;
                changeIntegral = newIntegral - oldIntegral;
                aspectOperatorLog = aspectOperatorLog + "；修改积分:" + integral;
            }

            wxpubUser.setIntegral(newIntegral);
            content.append("变动积分:" + changeIntegral).append(";");
        }

        Integer nowTime = DateUtil.getNowTime();
        wxpubUser.setUpdateTime(nowTime);
        int j = wxpubUserMapper.updateBalance(wxpubUser);
        if (j != 1) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
        }

        //增加账号入账明细
        UserAccDetail wxpubUserAccDetail = new UserAccDetail();
        wxpubUserAccDetail.setId(IdWorker.getId());
        wxpubUserAccDetail.setMerId(wxpubUser.getMerId());
        wxpubUserAccDetail.setUserId(wxpubUser.getId());
        wxpubUserAccDetail.setDeviceUniqueId(wxpubUser.getDeviceUniqueId());
        wxpubUserAccDetail.setDeviceType(wxpubUser.getDeviceType());
        wxpubUserAccDetail.setChangeInte(wxpubUserUpdateBalanceDto.getIntegral());
        wxpubUserAccDetail.setChangeBal(wxpubUserUpdateBalanceDto.getBalance());
        wxpubUserAccDetail.setNewBal(wxpubUser.getBalance());
        wxpubUserAccDetail.setNewInte(wxpubUser.getIntegral());
        wxpubUserAccDetail.setType(AccDetailTypeEnum.CHANGE_OPERATOR.getValue());
        wxpubUserAccDetail.setRemark(wxpubUserUpdateBalanceDto.getRemark());
        wxpubUserAccDetail.setCreateTime(nowTime);
        wxpubUserAccDetail.setUpdateTime(nowTime);
        //插入用户账户明细记录
        int insert = userAccDetailMapper.insert(wxpubUserAccDetail);
        if(insert!=1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
        }

        //AOP切面，封装操作日志内容
        wxpubUserUpdateBalanceDto.setAspectOperatorLog(aspectOperatorLog);

        //发送异常报警通知-修改会员敏感信息
        AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
        alarmMsgFeignDto.setMerId(wxpubUserUpdateBalanceDto.getMerId());
        alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER_BAL_INTE.getValue()); //修改会员敏感信息
        //消息
        JSONObject ext = new JSONObject();
        //当前操作员
        String token_key = String.format(CacheKey.LOGIN_TOKEN, wxpubUserUpdateBalanceDto.getLoginToken());
        Object data = redisTemplate.opsForValue().get(token_key);
        LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
        if(loginVo == null){
            loginVo = new LoginVo();
        }
        ext.put("childuser", loginVo.getLoginName());
        ext.put("content", content.toString());
        ext.put("nick", wxpubUser.getNickName());
        ext.put("wxid", wxpubUser.getBizUserId());
        ext.put("userid", wxpubUser.getId());
        ext.put("phone", loginVo.getMobile());
        alarmMsgFeignDto.setExt(ext.toJSONString());
//        UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//        logger.info("---发送修改会员余额和积分报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

        //2024-01-09修改成直接发送MQ
        noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

    }

    @Override
    public WxpubUserInfoVo updateUserInfoFromWechat(WxpubUserInfoVo wxpubUserIdDto) {
        return null;
    }

    @Override
    @Transactional
    public void updateToOneUser(WxpubUserUpdateDto wxpubUserUpdateDto) {
        if (wxpubUserUpdateDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户ID不存在");
        }

        WxpubUser wxpubUser = wxpubUserMapper.selectById(wxpubUserUpdateDto.getId(), wxpubUserUpdateDto.getMerId());

        if (wxpubUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户不存在");
        }

        //修改定向规则
        //获取用户本身旧的定向规则JSON对象
        Map<String, PriRewardRulesDto> priRewardRulesMap_old = JSONObject.parseObject(wxpubUser.getPriRewardRules(), new TypeReference<Map<String, PriRewardRulesDto>>(){});
        if(priRewardRulesMap_old == null){
            priRewardRulesMap_old = new HashMap<>();
        }

        //获取页面设置的新的定向规则JSON对象
        Map<String, PriRewardRulesDto> priRewardRulesMap_new = JSONObject.parseObject(wxpubUserUpdateDto.getPriRewardRules(), new TypeReference<Map<String, PriRewardRulesDto>>(){});
        if(priRewardRulesMap_new != null && priRewardRulesMap_new.size() > 0){
            for(String key : priRewardRulesMap_new.keySet()){
                //新定向规则
                PriRewardRulesDto priRewardRulesDto_new = priRewardRulesMap_new.get(key);
                //旧定向规则
                PriRewardRulesDto priRewardRulesDto_old = priRewardRulesMap_old.get(key);
                if(priRewardRulesDto_old == null){
                    priRewardRulesDto_old = new PriRewardRulesDto();
                }
                //判断新的定向规则值
                if(priRewardRulesDto_new != null){
                    //判断定向规则
                    if(priRewardRulesDto_new.getPriRuleId() != null){ //表示修改
                        if(priRewardRulesDto_new.getPriRuleId().longValue() < 0){ //表示清空
                            priRewardRulesDto_old.setPriRuleId(null);
                        }else{//表示修改
                            priRewardRulesDto_old.setPriRuleId(priRewardRulesDto_new.getPriRuleId());
                        }
                    }
                    //判断阶梯规则
                    if(priRewardRulesDto_new.getLadderId() != null){ //表示修改
                        if(priRewardRulesDto_new.getLadderId().longValue() < 0){ //表示清空
                            priRewardRulesDto_old.setLadderId(null);
                        }else{//表示修改
                            priRewardRulesDto_old.setLadderId(priRewardRulesDto_new.getLadderId());
                        }
                    }
                }
                //更新旧的定向规则
                priRewardRulesMap_old.put(key, priRewardRulesDto_old);
            }
        }
        //修改时间
        Integer nowTime = DateUtil.getNowTime();
        wxpubUser.setUpdateTime(nowTime);
        //修改定向规则
        wxpubUser.setPriRewardRules(Tools.getStrEmpty(JSONObject.toJSONString(priRewardRulesMap_old)));
        wxpubUserMapper.updatePriRewardRules(wxpubUser);

        //是否增加新标签列表
        List<String> userLabList = wxpubUserUpdateDto.getUserLabList();
        //是否清空所有标签
        Integer cleanLab = wxpubUserUpdateDto.getCleanLab();
        //清空指定标签列表
        List<String> cleanUserLabList = wxpubUserUpdateDto.getCleanUserLabList();

        //开启清空所有标签
        if(cleanLab != null && cleanLab.intValue() == 1){
            //添加新标签
            if(userLabList != null && userLabList.size() > 0){
                wxpubUser.setTags(JSONObject.toJSONString(userLabList));
            }else{
                wxpubUser.setTags("");
            }
        }else{ //未开启清空标签
            //旧标签
            String tags_old = wxpubUser.getTags();
            List<String> tagsOldList = JSONObject.parseArray(tags_old, String.class);
            if(tagsOldList == null){
                tagsOldList = new ArrayList<>();
            }

            //清空指定标签列表
            if(cleanUserLabList != null && cleanUserLabList.size() > 0){
                tagsOldList.removeAll(cleanUserLabList);
            }

            //添加新标签
            if(userLabList != null && userLabList.size() > 0){
                tagsOldList.addAll(userLabList);
            }

            //去重复
            tagsOldList = tagsOldList.stream().distinct().collect(Collectors.toList());
            wxpubUser.setTags(JSONObject.toJSONString(tagsOldList));
        }

        //是否增加新会员标签列表
        List<SysTagVo> sysTagsList = wxpubUserUpdateDto.getSysTagsList();
        //是否清空所有会员标签
        Integer cleanSysTags = wxpubUserUpdateDto.getCleanSysTags();
        //清空指定会员标签列表
        List<SysTagVo> cleanSysTagsList = wxpubUserUpdateDto.getCleanSysTagsList();

        //开启清空所有会员标签
        if(cleanSysTags != null && cleanSysTags.intValue() == 1){
            //添加新会员标签
            if(sysTagsList != null && sysTagsList.size() > 0){
                wxpubUser.setSysTags(JSONObject.toJSONString(sysTagsList));
            }else{
                wxpubUser.setSysTags("");
            }
        }else{//未开启清空会员标签
            //旧会员标签
            String sysTags_old = wxpubUser.getSysTags();
            List<SysTagVo> sysTagsOldList = JSONObject.parseArray(sysTags_old, SysTagVo.class);
            if(sysTagsOldList == null){
                sysTagsOldList = new ArrayList<>();
            }

            //清空指定会员标签列表
            if(cleanSysTagsList != null && cleanSysTagsList.size() > 0){
                sysTagsOldList.removeAll(cleanSysTagsList);
            }

            //添加新会员标签
            if(sysTagsList != null && sysTagsList.size() > 0){
                if(sysTagsOldList.size() == 0){
                    sysTagsOldList.addAll(sysTagsList);
                }else{
                    //循环遍历，一个个增加,如果类型存在，则删除
                    for (SysTagVo sysTagVo : sysTagsList) {
                        for (int i = sysTagsOldList.size()-1; i>=0 ; i--) {
                            //如果标签类型相等，则删除旧标签
                            if(sysTagsOldList.get(i).getType().intValue() == sysTagVo.getType().intValue()){
                                sysTagsOldList.remove(i);
                            }else{
                                if(sysTagVo.getType().intValue() == MarketingTagTypeEnum.TAKETAL_NEED_EXAMINE_VALUE){
                                    if(sysTagsOldList.get(i).getType().intValue() == MarketingTagTypeEnum.TAKETAL_NOT_EXAMINE_VALUE){
                                        sysTagsOldList.remove(i);
                                    }
                                }else if(sysTagVo.getType().intValue() == MarketingTagTypeEnum.TAKETAL_NOT_EXAMINE_VALUE){
                                    if(sysTagsOldList.get(i).getType().intValue() == MarketingTagTypeEnum.TAKETAL_NEED_EXAMINE_VALUE){
                                        sysTagsOldList.remove(i);
                                    }
                                }
                            }
                        }
                    }
                    sysTagsOldList.addAll(sysTagsList);
                }
            }

            //去重复
            sysTagsOldList = sysTagsOldList.stream().distinct().collect(Collectors.toList());
            wxpubUser.setSysTags(JSONObject.toJSONString(sysTagsOldList));
        }

        //是否修改备注
        Boolean setRemarkFlag = false;
        String userRemark = wxpubUserUpdateDto.getUserRemark();
        if(org.apache.commons.lang3.StringUtils.isNotBlank(userRemark)){
            //替换变量
            userRemark = userRemark.replaceFirst("\\[昵称\\]", wxpubUser.getNickName());
            wxpubUser.setRemark(Tools.getStr(userRemark));
            setRemarkFlag = true;
        }

        wxpubUserMapper.updateRemarkAndTags(wxpubUser);

        //是否修改了用户备注，如果修改了，则发送MQ同步手机微信好友，
        if(setRemarkFlag){
            //查询机器人
            WxpubInfoEntity wxpubInfoEntity = wxpubInfoMapper.queryObject(wxpubUser.getDeviceUniqueId());
            if(wxpubInfoEntity != null){
                //发送MQ消息
                MsgDto<SetUserRemarkDto> msgDto = new MsgDto<>();
                SetUserRemarkDto setUserRemarkDto = new SetUserRemarkDto();
                msgDto.setContent(setUserRemarkDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceUniqueId(wxpubUser.getDeviceUniqueId());
                msgDto.setDeviceType(DeviceTypeEnum.WX_PUB_VALUE);
                msgDto.setMerId(wxpubUser.getMerId());
                msgDto.setMsgType(MessageFuncEnum.SET_USER_REMARK.getValue());
                setUserRemarkDto.setWxid(wxpubUser.getBizUserId());
                setUserRemarkDto.setRemark(Tools.getStr(wxpubUser.getRemark()));
                noticeMsgPushProducerService.setUserRemark(msgDto);
            }
        }

        //计算用户余额并修改
        //变更余额
        Double balance = wxpubUserUpdateDto.getBalance();
        //变更积分
        Integer integral = wxpubUserUpdateDto.getIntegral();
        //积分和余额只要有一个不等于null。表示有变更，则修改
        if(balance != null || integral != null){

            //发送修改会员数据提醒通知
            StringBuffer content = new StringBuffer("正在修改会员余额和积分;");

            wxpubUser.setUpdateTime(nowTime);
            Double changeBalance = 0.0D;
            //表示修改余额
            if(balance != null){
                //修改类型类型
                Integer balanceType = wxpubUserUpdateDto.getBalanceType();
                //旧余额
                Double oldBalance = Tools.getDouble(wxpubUser.getBalance());
                //新余额
                Double newBalance = 0.00D;
                if(balanceType.intValue() == -1){ //减量
                    //减少
                    newBalance = Math.sub(oldBalance, balance);
                    changeBalance = Math.sub(0, balance);
                }else if(balanceType.intValue() == 1){ //增量
                    //增加
                    newBalance = Math.add(oldBalance, balance);
                    changeBalance = balance;
                }else{//修改成指定值
                    newBalance = balance;
                    changeBalance = Math.sub(newBalance, oldBalance);
                }
                wxpubUser.setBalance(newBalance);
                content.append("变动余额:" + changeBalance).append(";");
            }

            //变更积分
            Integer changeIntegral = 0;
            if(integral != null) {
                //修改积分类型
                Integer integralType = wxpubUserUpdateDto.getIntegralType();
                //旧积分
                Integer oldIntegral = Tools.getInteger(wxpubUser.getIntegral());
                //新积分
                Integer newIntegral = 0;

                if(integralType.intValue() == -1){ //减量
                    //减少
                    newIntegral = oldIntegral - integral;
                    changeIntegral = 0 - integral;
                }else if(integralType.intValue() == 1){ //增量
                    //增加
                    newIntegral = oldIntegral + integral;
                    changeIntegral = integral;
                }else{//修改成指定值
                    newIntegral = integral;
                    changeIntegral = newIntegral - oldIntegral;
                }

                wxpubUser.setIntegral(newIntegral);
                content.append("变动积分:" + changeIntegral).append(";");
            }

            int j = wxpubUserMapper.updateBalance(wxpubUser);
            if (j != 1) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
            }
            //增加账号入账明细
            UserAccDetail wxpubUserAccDetail = new UserAccDetail();
            wxpubUserAccDetail.setId(IdWorker.getId());
            wxpubUserAccDetail.setMerId(wxpubUser.getMerId());
            wxpubUserAccDetail.setUserId(wxpubUser.getId());
            wxpubUserAccDetail.setDeviceUniqueId(wxpubUser.getDeviceUniqueId());
            wxpubUserAccDetail.setDeviceType(wxpubUser.getDeviceType());
            wxpubUserAccDetail.setChangeInte(changeIntegral);
            wxpubUserAccDetail.setChangeBal(changeBalance);
            wxpubUserAccDetail.setNewBal(wxpubUser.getBalance());
            wxpubUserAccDetail.setNewInte(wxpubUser.getIntegral());
            wxpubUserAccDetail.setType(AccDetailTypeEnum.CHANGE_OPERATOR.getValue());
            wxpubUserAccDetail.setRemark("运营商批量修改");
            wxpubUserAccDetail.setCreateTime(nowTime);
            wxpubUserAccDetail.setUpdateTime(nowTime);
            //插入用户账户明细记录
            int insert = userAccDetailMapper.insert(wxpubUserAccDetail);
            if(insert!=1){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
            }

            //发送异常报警通知-修改会员敏感信息
            AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
            alarmMsgFeignDto.setMerId(wxpubUser.getMerId());
            alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER_BAL_INTE.getValue()); //修改会员敏感信息
            //消息
            JSONObject ext = new JSONObject();
            //当前操作员
            String token_key = String.format(CacheKey.LOGIN_TOKEN, wxpubUserUpdateDto.getLoginToken());
            Object data = redisTemplate.opsForValue().get(token_key);
            LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
            if(loginVo == null){
                loginVo = new LoginVo();
            }
            ext.put("childuser", loginVo.getLoginName());
            ext.put("content", content.toString());
            ext.put("nick", wxpubUser.getNickName());
            ext.put("wxid", wxpubUser.getBizUserId());
            ext.put("userid", wxpubUser.getId());
            ext.put("phone", loginVo.getMobile());
            alarmMsgFeignDto.setExt(ext.toJSONString());
//            UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//            logger.info("---发送修改会员余额和积分报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

            //2024-01-09修改成直接发送MQ
            noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

        }

        //是否加入黑名单
        if(wxpubUserUpdateDto.getUserBlackType() != null){
            //查询是否已经在黑名单当中
            //id为merId_wxid
            String id = wxpubUser.getMerId() + "_" + wxpubUser.getBizUserId();
            Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id, null);
            WechatBlacklistPrv wechatBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WechatBlacklistPrv.class);
            //不存在，则表示还未加入黑名单，则加入
            if(wechatBlacklistPrv == null){
                wechatBlacklistPrv = new WechatBlacklistPrv();
                wechatBlacklistPrv.setId(id);
                wechatBlacklistPrv.setMerId(wxpubUser.getMerId());
                wechatBlacklistPrv.setDeviceUniqueId(wxpubUser.getDeviceUniqueId());
                wechatBlacklistPrv.setDeviceType(wxpubUser.getDeviceType());
                wechatBlacklistPrv.setWxid(wxpubUser.getBizUserId());
                wechatBlacklistPrv.setNickName(wxpubUser.getNickName());
                wechatBlacklistPrv.setHeadImg(wxpubUser.getHeadImg());
                wechatBlacklistPrv.setType(wxpubUserUpdateDto.getUserBlackType());
                wechatBlacklistPrv.setRemark(wxpubUserUpdateDto.getUserBlackRemark());
                wechatBlacklistPrv.setCreateTime(nowTime);
                wechatBlacklistPrv.setUpdateTime(nowTime);
                elasticsearchUtil.addData(wechatBlacklistPrv, EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id);
            }

            //添加到全网黑名单
            if(wxpubUserUpdateDto.getAllBackFlag() != null && wxpubUserUpdateDto.getAllBackFlag().intValue() == 1){
                Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, wxpubUser.getBizUserId(), null);
                WechatBlacklistPub wechatBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WechatBlacklistPub.class);
                //全网黑名单中不存在
                if(wechatBlacklistPub == null){
                    wechatBlacklistPub = new WechatBlacklistPub();
                    BeanUtils.copyProperties(wechatBlacklistPrv, wechatBlacklistPub);
                    wechatBlacklistPub.setId(wxpubUser.getBizUserId());
                    wechatBlacklistPub.setCreateTime(nowTime);
                    wechatBlacklistPub.setUpdateTime(nowTime);
                    //数据来源(0运营商共享 1官方采集-免费  2收费名单)
                    wechatBlacklistPub.setSource(0);
                    //增加到全网黑名单
                    elasticsearchUtil.addData(wechatBlacklistPub, EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, wxpubUser.getBizUserId());
                }
            }
        }

        //是否加入提现黑名单
        if(Tools.getInteger(wxpubUserUpdateDto.getTakeBalBlackFlag()).intValue() == 1){//开启加入提现黑名单

            //判断会员id是否已经在黑名单当中
            TakeBalBlacklist takeBalBlacklist_old = takeBalBlacklistMapper.selectByUserId(wxpubUserUpdateDto.getId(), wxpubUserUpdateDto.getMerId());
            //不存在，则加入黑名单当中
            if(takeBalBlacklist_old == null){
                TakeBalBlacklist takeBalBlacklist = new TakeBalBlacklist();
                takeBalBlacklist.setUserId(wxpubUserUpdateDto.getId());
                takeBalBlacklist.setMerId(wxpubUserUpdateDto.getMerId());
                takeBalBlacklist.setNickName(wxpubUser.getNickName());
                takeBalBlacklist.setDeviceType(wxpubUser.getDeviceType());
                takeBalBlacklist.setRemark(wxpubUserUpdateDto.getTakeBalBlackRemark());
                takeBalBlacklist.setAlipayAccount(wxpubUser.getAlipayAccount());
                takeBalBlacklist.setId(IdWorker.getId());
                takeBalBlacklist.setCreateTime(nowTime);
                takeBalBlacklist.setUpdateTime(nowTime);
                //保存加入提现黑名单
                takeBalBlacklistMapper.insert(takeBalBlacklist);
            }
        }

        //营销奖励黑名单
        try {
            marketingRewardsBlackListService.addOrRemoveByFlag(wxpubUser.getMerId(), String.valueOf(wxpubUser.getId()), wxpubUserUpdateDto.getMarketingRewardsBlackListRemark(), wxpubUserUpdateDto.getMarketingRewardsBlackListFlag(),
                    wxpubUserUpdateDto.getSubNotPassFriend());
        }catch (Exception e){

        }

    }


    /**
     * 修改微信用户详情信息
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxpubUserInfoUpdateDto
     * @return null
     */
    @Transactional
    public void updateWxpubUserInfo(WxpubUserInfoUpdateDto wxpubUserInfoUpdateDto){

        if(wxpubUserInfoUpdateDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WxpubUser wxpubUser = wxpubUserMapper.selectById(wxpubUserInfoUpdateDto.getId(), wxpubUserInfoUpdateDto.getMerId());

        if(wxpubUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //获取运营商ID
        Long merId = wxpubUser.getMerId();
        //用户Id
        Long id = wxpubUser.getId();


        //微信昵称
        if(!Tools.getStr(wxpubUserInfoUpdateDto.getNickName()).equals(Tools.getStr(wxpubUser.getNickName()))){
            wxpubUser.setNickName(Tools.getStr(wxpubUserInfoUpdateDto.getNickName()));
        }

        //会员类型
        wxpubUser.setUserType(wxpubUserInfoUpdateDto.getUserType());

        //支付宝姓名
        Boolean updateAlipayInfoFlag = false;
        if(!Tools.getStr(wxpubUserInfoUpdateDto.getAlipayName()).equals(Tools.getStr(wxpubUser.getAlipayName()))){
            wxpubUser.setAlipayName(wxpubUserInfoUpdateDto.getAlipayName());
            updateAlipayInfoFlag = true;
        }

        //支付宝账号
        if(!Tools.getStr(wxpubUserInfoUpdateDto.getAlipayAccount()).equals(Tools.getStr(wxpubUser.getAlipayAccount()))){
            wxpubUser.setAlipayAccount(wxpubUserInfoUpdateDto.getAlipayAccount());
            updateAlipayInfoFlag = true;
        }

        //淘宝订单尾号
//        if(Tools.getInteger(wxpubUserInfoUpdateDto.getTbLastOrderNo()).intValue() != Tools.getInteger(wxpubUser.getTbLastOrderNo()).intValue()){
//            wxpubUser.setTbLastOrderNo(Tools.getInteger(wxpubUserInfoUpdateDto.getTbLastOrderNo()));
//        }

        //最后下单时间
        if(Tools.getInteger(wxpubUserInfoUpdateDto.getLastOrderTime()).intValue() != Tools.getInteger(wxpubUser.getLastOrderTime()).intValue()){
            wxpubUser.setLastOrderTime(Tools.getInteger(wxpubUserInfoUpdateDto.getLastOrderTime()));
        }

        //机器人ID
        wxpubUser.setDeviceUniqueId(wxpubUserInfoUpdateDto.getDeviceUniqueId());

        //标签
        List<String> addTagsList = wxpubUserInfoUpdateDto.getTagsArr();
        wxpubUser.setTags(Tools.getStrEmpty(JSONObject.toJSONString(addTagsList)));

        //会员标签
        List<SysTagVo> sysTagsList = wxpubUserInfoUpdateDto.getSysTagsList();
        String sysTagsStr = Tools.getStrEmpty(JSONObject.toJSONString(sysTagsList));
        if(!sysTagsStr.equals(Tools.getStrEmpty(wxpubUser.getSysTags()))){
            wxpubUser.setSysTags(sysTagsStr);
        }

        //是否修改备注
        Boolean setRemarkFlag = false;
        if(!Tools.getStr(wxpubUserInfoUpdateDto.getRemark()).equals(Tools.getStr(wxpubUser.getRemark()))){ //修改了备注
            //备注
            wxpubUser.setRemark(wxpubUserInfoUpdateDto.getRemark());
            setRemarkFlag = true;
        }


        //身份
        if(wxpubUserInfoUpdateDto.getIdentity() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "身份不能为空");
        }

        //是否修改身份证标志
        boolean flag_identity = false;
        //旧身份
        int identityOld = wxpubUser.getIdentity().intValue();
        //新身份
        int identityNew = wxpubUserInfoUpdateDto.getIdentity().intValue();

        //旧上级买家
        long parentIdOld = Tools.getLong(wxpubUser.getParentId()).longValue();

        //旧代理
        long agentIdOld = Tools.getLong(wxpubUser.getAgentId()).longValue();

        //旧合伙人
        long partnerIdOld = Tools.getLong(wxpubUser.getPartnerId()).longValue();

        //旧身份自己买家树
        String parentInfoOld_wo = Tools.getStr(wxpubUser.getParentInfo());

        //旧身份的所有下级的上级买家树
        String parentInfoOld_son = null;
        if(parentIdOld != 0){
            parentInfoOld_son = Tools.getStrConnect(String.valueOf(wxpubUser.getId()), "_", parentInfoOld_wo);
        }else{
            parentInfoOld_son = String.valueOf(wxpubUser.getId());
        }

        //旧身份自己的代理树
        String agentInfoOld_wo = Tools.getStr(wxpubUser.getAgentInfo());

        //旧身份的下级的代理树
        String agentInfoOld_son = null;
        if(agentIdOld != 0){
            agentInfoOld_son = Tools.getStrConnect(String.valueOf(wxpubUser.getId()), "_", agentInfoOld_wo);
        }else{
            agentInfoOld_son = String.valueOf(wxpubUser.getId());
        }

        //如果新身份是合伙人：合伙人、代理、上级买家全部清空
        if(identityNew == IdentityEnum.PARTNER.getId()){
            wxpubUserInfoUpdateDto.setPartnerId(0L); //修改合伙人
            wxpubUserInfoUpdateDto.setAgentId(0L); //修改代理
            wxpubUserInfoUpdateDto.setParentId(0L); //修改上级买家
        }else if(identityNew == IdentityEnum.AGENT.getId()){ //如果新身份是代理：上级买家清空
            wxpubUserInfoUpdateDto.setParentId(0L);
        }

        //判断是否修改了身份
        if(identityNew != identityOld){ //修改身份
            flag_identity = true;       //修改身份标志为true
            wxpubUser.setIdentity(identityNew); //修改身份属性值
        }

        //新上级买家
        long parentIdNew = Tools.getLong(wxpubUserInfoUpdateDto.getParentId()).longValue();

        //新代理
        long agentIdNew = Tools.getLong(wxpubUserInfoUpdateDto.getAgentId()).longValue();

        //新合伙人
        long partnerIdNew = Tools.getLong(wxpubUserInfoUpdateDto.getPartnerId()).longValue();

        //验证合伙人ID是否为合伙人
        boolean flag_partner = false;
        if(partnerIdNew != partnerIdOld){ //修改了合伙人

            //标志合伙人已经修改
            flag_partner = true;

            wxpubUser.setPartnerId(partnerIdNew); //修改自己的合伙人信息
            //选择了合伙人，验证对方身份
            if(partnerIdNew != 0 ){
                WxpubUser wxpubUserPartner_new = wxpubUserMapper.selectById(partnerIdNew, wxpubUserInfoUpdateDto.getMerId());
                //判断存不存在
                if(wxpubUserPartner_new == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不存在");
                }
                //判断身份
                if(wxpubUserPartner_new.getIdentity() == null || wxpubUserPartner_new.getIdentity().intValue() != IdentityEnum.PARTNER.getId()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不是合伙人身份");
                }
                //判断是否为自己
                if (wxpubUserPartner_new.getId().longValue() == wxpubUser.getId().longValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不能是自己本身");
                }
            }
        }

        //验证上级会员ID是否为买家
        boolean flag_parent = false;
        String parentInfoNew_wo = parentInfoOld_wo;   //默认新的等于旧的，如果修改了，则变成新的
        String parentInfoNew_son = parentInfoOld_son; //默认新的等于旧的，如果修改了，则变成新的
        if(parentIdNew != parentIdOld){//修改了上级买家
            //标志上级买家已经修改
            flag_parent = true;
            //修改上级买家ID
            wxpubUser.setParentId(parentIdNew);
            //验收上级买家
            if(parentIdNew != 0){ //选择了上级买家
                WxpubUser wxpubUserParent_new = wxpubUserMapper.selectById(parentIdNew, wxpubUserInfoUpdateDto.getMerId());
                //判断存不存在
                if(wxpubUserParent_new == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不存在");
                }
                //判断身份
                if(wxpubUserParent_new.getIdentity() == null || wxpubUserParent_new.getIdentity().intValue() != IdentityEnum.BUYER.getId()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不是买家身份");
                }
                //判断是否为自己
                if (wxpubUserParent_new.getId().longValue() == wxpubUser.getId().longValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不能是自己本身");
                }

                //判断上级是否为自己的下级，如果是自己的下级，则上级树中包含自己的ID
                String parentInfo = Tools.getStr(wxpubUserParent_new.getParentInfo());
                if(parentInfo.contains(String.valueOf(wxpubUser.getId()))){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不能是自己的下级买家");
                }
                //判断新上级买家是否有上级买家，
                if(Tools.getLong(wxpubUserParent_new.getParentId()).longValue() != 0){//如果新上级买家有上级买家
                    parentInfoNew_wo = Tools.getStrConnect(String.valueOf(wxpubUserParent_new.getId()), "_", wxpubUserParent_new.getParentInfo());
                    wxpubUser.setParentInfo(parentInfoNew_wo);
                }else{
                    parentInfoNew_wo = String.valueOf(wxpubUserParent_new.getId());
                    wxpubUser.setParentInfo(parentInfoNew_wo);
                }
                //所有下级的新的上级买家树
                parentInfoNew_son = Tools.getStrConnect(String.valueOf(wxpubUser.getId()), "_", parentInfoNew_wo);
            }else{ //取消了上级买家
                //修改自己的上级树
                parentInfoNew_wo = "";
                wxpubUser.setParentInfo(parentInfoNew_wo);
                //所有下级新的上级买家树
                parentInfoNew_son = String.valueOf(wxpubUser.getId());
            }
        }

        //验证代理身份是否为代理人
        boolean flag_agent = false;
        String agentInfoNew_wo = agentInfoOld_wo;    //默认新的等于旧的，如果修改了，则变成新的
        String agentInfoNew_son = agentInfoOld_son;  //默认新的等于旧的，如果修改了，则变成新的
        if(agentIdNew != agentIdOld){ //表示修改了上级代理
            //标志上级代理已经修改
            flag_agent = true;
            //修改代理属性
            wxpubUser.setAgentId(agentIdNew);

            if(agentIdNew != 0 ){ //选择了上级代理，需要验证身份
                WxpubUser wxpubUserAgent_new = wxpubUserMapper.selectById(agentIdNew, wxpubUserInfoUpdateDto.getMerId());
                //判断存不存在
                if(wxpubUserAgent_new == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该代理人不存在");
                }
                //判断身份
                if(wxpubUserAgent_new.getIdentity() == null || wxpubUserAgent_new.getIdentity().intValue() != IdentityEnum.AGENT.getId()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该代理人不是代理人身份");
                }

                //判断是否为自己
                if (wxpubUserAgent_new.getId().longValue() == wxpubUser.getId().longValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级代理不能是自己本身");
                }

                //判断上级是否为自己的下级，如果是自己的下级，则上级树中包含自己的ID
                String agentInfo = Tools.getStr(wxpubUserAgent_new.getAgentInfo());
                if(agentInfo.contains(String.valueOf(wxpubUser.getId()))){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级代理不能是自己的下级代理");
                }

                //判断代理是否有上级代理
                if(Tools.getLong(wxpubUserAgent_new.getAgentId()) != 0){ //代理有上级代理
                    agentInfoNew_wo = Tools.getStrConnect(String.valueOf(wxpubUserAgent_new.getId()), "_", wxpubUserAgent_new.getAgentInfo());
                    wxpubUser.setAgentInfo(agentInfoNew_wo);
                }else{
                    agentInfoNew_wo = String.valueOf(wxpubUserAgent_new.getId());
                    wxpubUser.setAgentInfo(agentInfoNew_wo);
                }
                //所有下级的新的代理
                agentInfoNew_son = Tools.getStrConnect(String.valueOf(wxpubUser.getId()), "_", agentInfoNew_wo);
            }else{ //取消了上级买家
                //修改自己的上级树
                agentInfoNew_wo = "";
                wxpubUser.setAgentInfo(agentInfoNew_wo);
                //临时保存所有下级的新的代理树
                agentInfoNew_son = String.valueOf(wxpubUser.getId());
            }
        }

        //修改微信用户详情信息
        wxpubUserMapper.updateById(wxpubUser);

        //修改身份，改变了其他用户的树
        if(flag_identity){
            //判断旧身份类型
            if(identityOld == IdentityEnum.BUYER.getId()){ // 旧身份是买家
                //判断新身份
                if(identityNew == IdentityEnum.AGENT.getId()){ //新身份是代理

                    /**买家转代理-身份往上升
                     * 1: 批量将下N级无代理的用户代理设置为此Id，代理树也更新, 满足条件：A:买家树包含此ID，B：代理为空
                     * 2：修改下N级买家树（从此用户开始清空）
                     * 3: 修改下级的上级和买家树（全部清空）
                     */
                    //1: 批量将下N级无代理的用户代理设置为此Id，代理树也更新, 满足条件：A:买家树包含此ID，B：代理为空
                    wxpubUserMapper.batchUpdateAgentInfoFromParentInfo(id, agentInfoNew_son, merId);
                    //2：修改下N级买家树（从此用户开始清空）
                    wxpubUserMapper.batchUpdateParentInfo("_" + parentInfoOld_son, "", merId, true);
                    wxpubUserMapper.batchUpdateParentInfo(parentInfoOld_son, "", merId, false);
                    //3: 修改下级的上级和买家树（全部清空）
                    WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
                    wxpubUserQuery.setMerId(merId);
                    wxpubUserQuery.setParentId(id);
                    List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(wxpubUserQuery);
                    //3：循环List，得到单个用户，修改单个用户的代理和代理树，并清空其上级买家值和买家树；
                    if(wxpubUserList != null && wxpubUserList.size() > 0){
                        for(WxpubUser wxpubUser_son : wxpubUserList){
                            wxpubUser_son.setParentId(0L);   //清空上级
                            wxpubUser_son.setParentInfo(""); //清空上级树
                            wxpubUser_son.setAgentId(id);    //修改代理
                            wxpubUser_son.setAgentInfo(agentInfoNew_son); //修改代理树
                            wxpubUser_son.setUpdateTime(DateUtil.getNowTime());
                            wxpubUserMapper.updateIdentityInfo(wxpubUser_son);
                            //4：将下N级代理和下N级代理的树更新
                            String agentInfoOld_Nson = String.valueOf(wxpubUser_son.getId());
                            String agentInfoNew_Nson = wxpubUser_son.getId() + "_" + wxpubUser_son.getAgentInfo();
                            //分俩次替换（避免替换留下"_"符合）
                            wxpubUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                            wxpubUserMapper.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                        }
                    }

                }else if(identityNew == IdentityEnum.PARTNER.getId()){ //新身份是合伙人

                    /**买家转合伙人-身份往上升
                     * 1: 批量将下N级无合伙人的用户合伙人设置为此Id，满足条件：A:买家树包含此ID，B：合伙人为空
                     * 2：修改下N级买家树（从此用户开始清空）
                     * 3: 修改下级的上级和买家树（全部清空）
                     */
                    //1: 批量将下N级无合伙人的合伙人设置为此Id，满足条件：A:买家树包含此ID，B：合伙人为空
                    wxpubUserMapper.batchUpdatePartnerInfoFromParentInfo(id, merId);
                    //2：修改下N级买家树（从此用户开始清空）
                    wxpubUserMapper.batchUpdateParentInfo("_" + parentInfoOld_son, "", merId, true);
                    wxpubUserMapper.batchUpdateParentInfo(parentInfoOld_son, "", merId, false);
                    //3: 修改下级的上级和买家树（全部清空）
                    WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
                    wxpubUserQuery.setMerId(merId);
                    wxpubUserQuery.setParentId(id);
                    List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(wxpubUserQuery);
                    //3：循环List，得到单个用户，修改单个用户的代理和代理树，并清空其上级买家值和买家树；
                    if(wxpubUserList != null && wxpubUserList.size() > 0){
                        for(WxpubUser wxpubUser_son : wxpubUserList){
                            wxpubUser_son.setParentId(0L);   //清空上级
                            wxpubUser_son.setParentInfo(""); //清空上级树
                            wxpubUser_son.setPartnerId(id);    //修改合伙人
                            wxpubUser_son.setUpdateTime(DateUtil.getNowTime());
                            wxpubUserMapper.updateIdentityInfo(wxpubUser_son);
                        }
                    }
                }
            }else if(identityOld == IdentityEnum.AGENT.getId()){ //旧身份是代理
                //判断新身份
                if(identityNew == IdentityEnum.BUYER.getId()){ //新身份是买家

                    /**代理转买家-身份往下降
                     *  1: 批量将下N级代理无上级的买家，将上级设置为此Id，更新买家树，满足条件：A:代理树包含此ID，B：上级id为空；C：身份是买家
                     *  2：修改下N级代理树
                     *  3: 修改下级的代理和代理树
                     */

                    //1: 批量将下N级代理无上级的买家，将上级设置为此Id，更新买家树，满足条件：A:代理树包含此ID，B：上级id为空；C：身份是买家
                    //wxpubUserMapper.batchUpdateParentInfoFromAgentInfoAndParentIdNull(id, IdentityEnum.BUYER.getId(), parentInfoNew_son, merId, 0);

                    //2：修改下N级代理树
                    //分俩次替换（避免替换留下"_"符合）
                    wxpubUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_son, "_" + agentInfoNew_wo, merId, true);
                    wxpubUserMapper.batchUpdateAgentInfo(agentInfoOld_son, agentInfoNew_wo, merId, false);

                    //3: 修改下级的代理和代理树
                    WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
                    wxpubUserQuery.setMerId(merId);
                    wxpubUserQuery.setAgentId(id);
                    List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(wxpubUserQuery);
                    //3：循环List，得到单个用户，修改单个用户的买家和买家树，代理和代理树；
                    if(wxpubUserList != null && wxpubUserList.size() > 0){
                        for(WxpubUser wxpubUser_son : wxpubUserList){
                            wxpubUser_son.setAgentId(agentIdNew);           // 修改新的上级代理
                            wxpubUser_son.setAgentInfo(agentInfoNew_wo);    //修改新的代理树

                            //买家为空，且身份是买家
                            if(wxpubUser_son.getParentId().longValue() == 0L && wxpubUser_son.getIdentity().intValue() == IdentityEnum.BUYER.getId().intValue()){
                                wxpubUser_son.setParentId(id);                  //修改上级
                                wxpubUser_son.setParentInfo(parentInfoNew_son); //修改上级树
                                //将下N级上级和下N级的上级树更新
                                String parentInfoOld_Nson = String.valueOf(wxpubUser_son.getId());
                                String parentInfoNew_Nson = wxpubUser_son.getId() + "_" + wxpubUser_son.getParentInfo();
                                //分俩次替换（避免替换留下"_"符合）
                                wxpubUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                wxpubUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                            }

                            wxpubUser_son.setUpdateTime(DateUtil.getNowTime());
                            wxpubUserMapper.updateIdentityInfo(wxpubUser_son);

                        }
                    }

                }else if(identityNew == IdentityEnum.PARTNER.getId()){ //新身份是合伙人

                    /**代理转合伙人-身份往上升
                     *  1: 批量将下N级代理无上级的买家，将上级设置为此Id，更新买家树，满足条件：A:代理树包含此ID，B：上级id为空；C：身份是买家
                     *  2：修改下N级代理树
                     *  3: 修改下级的代理和代理树
                     */

                    //1: 批量将下N级代理无合伙人的会员，将合伙人设置为此Id，满足条件：A:代理树包含此ID，B：合伙人为空；
                    wxpubUserMapper.batchUpdatePartnerIdFromAgentInfo(id, merId);
                    //2：修改下N级代理树(清空截断）
                    //分俩次替换（避免替换留下"_"符合）
                    wxpubUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_son, "", merId, true);
                    wxpubUserMapper.batchUpdateAgentInfo(agentInfoOld_son, "", merId, false);
                    //3: 修改下级的代理和代理树
                    WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
                    wxpubUserQuery.setMerId(merId);
                    wxpubUserQuery.setAgentId(id);
                    List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(wxpubUserQuery);
                    //3：循环List，得到单个用户，修改单个用户的买家和买家树，代理和代理树；
                    if(wxpubUserList != null && wxpubUserList.size() > 0){
                        for(WxpubUser wxpubUser_son : wxpubUserList){
                            wxpubUser_son.setAgentId(0L);                    // 清空代理人
                            wxpubUser_son.setAgentInfo("");                  //清空代理人信息
                            wxpubUser_son.setPartnerId(id);                  //修改合伙人
                            wxpubUser_son.setUpdateTime(DateUtil.getNowTime());
                            wxpubUserMapper.updateIdentityInfo(wxpubUser_son);
                        }
                    }
                }
            }else{ //旧身份是合伙人
                //判断新身份
                if(identityNew == IdentityEnum.BUYER.getId()){ //新身份是买家

                    /**合伙人转买家-身份往下降
                     *  1: 批量将下N级合伙人无上级的买家，将上级设置为此Id，更新买家树，满足条件：A:合伙人id等于此ID，B：上级id为空；C：身份是买家
                     *  2：清空下N合伙人信息,更新买家信息
                     */

                    //1: 批量将下N级合伙人无上级的买家，将上级设置为此Id，更新买家树，满足条件：A:合伙人id等于此ID，B：上级id为空；C：身份是买家
                    //wxpubUserMapper.batchUpdateParentInfoFromPartnerIdAndParentIdNull(id, IdentityEnum.BUYER.getId(), parentInfoNew_son, merId, 0);
                    //2：清空下N合伙人信息,更新买家信息
                    WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
                    wxpubUserQuery.setMerId(merId);
                    wxpubUserQuery.setPartnerId(id);
                    List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(wxpubUserQuery);
                    if(wxpubUserList != null && wxpubUserList.size() > 0){
                        for(WxpubUser wxpubUser_son : wxpubUserList){

                            wxpubUser_son.setPartnerId(0L);                  // 清空合伙人

                            //上级不能为空，代理不能为空，且身份是买家
                            if(wxpubUser_son.getParentId().longValue() == 0L && wxpubUser_son.getAgentId().longValue() == 0L && wxpubUser_son.getIdentity().intValue() == IdentityEnum.BUYER.getId().intValue()){
                                wxpubUser_son.setParentId(id);                   //修改上级
                                wxpubUser_son.setParentInfo(parentInfoNew_son);  //修改上级树

                                //将下N级上级和下N级的上级树更新
                                String parentInfoOld_Nson = String.valueOf(wxpubUser_son.getId());
                                String parentInfoNew_Nson = wxpubUser_son.getId() + "_" + wxpubUser_son.getParentInfo();
                                //分俩次替换（避免替换留下"_"符合）
                                wxpubUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                wxpubUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                            }

                            wxpubUser_son.setUpdateTime(DateUtil.getNowTime());
                            wxpubUserMapper.updateIdentityInfo(wxpubUser_son);

                        }
                    }
                }else if(identityNew == IdentityEnum.AGENT.getId()){ //新身份是代理

                    /**合伙人转代理-身份往下降
                     *  1: 批量将下N级合伙人无上级的买家，将上级设置为此Id，更新买家树，满足条件：A:合伙人id等于此ID，B：上级id为空；C：身份是买家
                     *  2：清空下N合伙人信息,更新买家信息
                     */

                    //1: 批量将下N级合伙人无上级的买家，将上级设置为此Id，更新买家树，满足条件：A:合伙人id等于此ID，B：上级id为空；C：身份是买家
                    //wxpubUserMapper.batchUpdateAgentInfoFromPartnerIdAndAgentIdNull(id, parentInfoNew_son, merId, 0);
                    //2：清空下N合伙人信息,更新买家信息
                    WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
                    wxpubUserQuery.setMerId(merId);
                    wxpubUserQuery.setPartnerId(id);
                    List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(wxpubUserQuery);
                    if(wxpubUserList != null && wxpubUserList.size() > 0){
                        for(WxpubUser wxpubUser_son : wxpubUserList){

                            wxpubUser_son.setPartnerId(0L);                  // 清空合伙人

                            //上级不能为空，代理不能为空，且身份是代理
                            if(wxpubUser_son.getParentId().longValue() == 0L && wxpubUser_son.getAgentId().longValue() == 0L && wxpubUser_son.getIdentity().intValue() == IdentityEnum.AGENT.getId().intValue()){
                                wxpubUser_son.setAgentId(id);                   //修改代理
                                wxpubUser_son.setAgentInfo(agentInfoNew_son);  //修改代理树

                                //将下N级代理和下N级的代理树更新
                                String agentInfoOld_Nson = String.valueOf(wxpubUser_son.getId());
                                String agentInfoNew_Nson = wxpubUser_son.getId() + "_" + wxpubUser_son.getAgentInfo();
                                //分俩次替换（避免替换留下"_"符合）
                                wxpubUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                wxpubUserMapper.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                            }

                            wxpubUser_son.setUpdateTime(DateUtil.getNowTime());
                            wxpubUserMapper.updateIdentityInfo(wxpubUser_son);

                        }
                    }
                }
            }
        }

        //如果修改了上级买家,批量修改下N级买家树
        if(flag_parent){
            //分俩次替换（避免替换留下"_"符合）
            wxpubUserMapper.batchUpdateParentInfo("_" + parentInfoOld_son, "_" + parentInfoNew_son, merId, true);
            wxpubUserMapper.batchUpdateParentInfo(parentInfoOld_son, parentInfoNew_son, merId, false);
        }

        //如果修改了代理,批量修改下N级代理树
        if(flag_agent){
            //分俩次替换（避免替换留下"_"符合）
            wxpubUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_son, "_" + agentInfoNew_son, merId, true);
            wxpubUserMapper.batchUpdateAgentInfo(agentInfoOld_son, agentInfoNew_son, merId, false);
        }

        //是否修改了用户备注，如果修改了，则发送MQ同步手机微信好友，
        if(setRemarkFlag){
            //查询机器人
            WxpubInfoEntity wxpubInfoEntity = wxpubInfoMapper.queryObject(wxpubUser.getDeviceUniqueId());
            if(wxpubInfoEntity != null){
                //发送MQ消息
                MsgDto<SetUserRemarkDto> msgDto = new MsgDto<>();
                SetUserRemarkDto setUserRemarkDto = new SetUserRemarkDto();
                msgDto.setContent(setUserRemarkDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceUniqueId(wxpubUser.getDeviceUniqueId());
                msgDto.setDeviceType(DeviceTypeEnum.WX_PUB_VALUE);
                msgDto.setMerId(wxpubUser.getMerId());
                msgDto.setMsgType(MessageFuncEnum.SET_USER_REMARK.getValue());
                setUserRemarkDto.setWxid(wxpubUser.getWxid());
                setUserRemarkDto.setRemark(Tools.getStr(wxpubUser.getRemark()));
                noticeMsgPushProducerService.setUserRemark(msgDto);
            }
        }

        //是否修改了支付宝账号和姓名
        if(updateAlipayInfoFlag){
            AlipayUserAuthDto alipayUserAuthDto = new AlipayUserAuthDto();
            alipayUserAuthDto.setAlipayUserId(wxpubUser.getAlipayAccount());
            alipayUserAuthDto.setAlipayUserName(wxpubUser.getAlipayName());
            alipayUserAuthDto.setUserId(String.valueOf(wxpubUser.getId()));
            //获取该会员的appid配置1-获取默认机器人;2-获取机器人的配置方案；3-从配置方案的提现配置里获取appid
            if(wxpubUser.getDeviceUniqueId() != null){
                WxpubInfoEntity wxpubInfoEntity = wxpubInfoMapper.queryObject(wxpubUser.getDeviceUniqueId());
                if(wxpubInfoEntity != null && wxpubInfoEntity.getConfigId() != null){
                    ConfigPlan configPlan = configPlanMapper.selectById(wxpubInfoEntity.getConfigId(), wxpubInfoEntity.getMerId());
                    if(configPlan != null && configPlan.getUserTakeBalId() != null){
                        SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserTakeBalId(), configPlan.getMerId());
                        if(sysPlugin != null && org.apache.commons.lang3.StringUtils.isNotBlank(sysPlugin.getData())){
                            try {
                                JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
                                String zf_app_id = jsonObject.getString("zf_app_id");//账房appId
                                if(org.apache.commons.lang3.StringUtils.isNotBlank(zf_app_id)){
                                    alipayUserAuthDto.setAppId(zf_app_id);
                                    UzaiRespVo<Object> objectUzaiRespVo = uzaiCashierServerFeignService.alipayUserAuth(alipayUserAuthDto);
                                    logger.info("--调用账房授权支付宝账号信息微服务接口--para={},result={}", JSONObject.toJSONString(alipayUserAuthDto), JSONObject.toJSONString(objectUzaiRespVo));
                                }
                            }catch (Exception e){
                                logger.error("---配置方案的提现设置插件格式有问题---sysPluginId={}, configId={}, merId={}", sysPlugin.getId(), configPlan.getId(), configPlan.getMerId());
                            }
                        }
                    }
                }
            }
        }

        //修改ES
        try{
            //修改营销策略数据
            if(flag_parent || flag_agent || flag_partner){
                marketingRewardsService.updateMarketingRewards(wxpubUser);
            }

            //修改会员扩展信息
            String uzai_user_ext_info_id = DeviceTypeEnum.WX_PUB.getKey() + "_" + wxpubUser.getMerId() + "_" + wxpubUser.getBizUserId();
            //查询会员基本信息
            Map<String,Object> dataMp_ext = elasticsearchUtil.searchDataById(merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wxpubUser.getMerId()), uzai_user_ext_info_id, null);
            if(dataMp_ext != null){
                EsUserExtInfo esUserExtInfo = new EsUserExtInfo();
                BeanUtils.copyProperties(wxpubUser, esUserExtInfo);
                esUserExtInfo.setId(uzai_user_ext_info_id);
                elasticsearchUtil.updateDataById(esUserExtInfo, merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wxpubUser.getMerId()), uzai_user_ext_info_id);
            }

            //解决ES延时删除
            Thread.sleep(1000);

        }catch (Exception e){
            logger.error("修改会员营销策略信息出现异常:{}"+ e.getMessage());
        }


    }


    /**
     * 修改微信用户定向比例
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxpubUserUpdatePriRewardRulesDto
     * @return null
     */
    public void updateWxpubUserPriRewardRules(WxpubUserUpdatePriRewardRulesDto wxpubUserUpdatePriRewardRulesDto){
        if(wxpubUserUpdatePriRewardRulesDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WxpubUser wxpubUser = wxpubUserMapper.selectById(wxpubUserUpdatePriRewardRulesDto.getId(), wxpubUserUpdatePriRewardRulesDto.getMerId());

        if(wxpubUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //获取设置定向规则JSON对象
        Map<String,PriRewardRulesDto> priRewardRules = JSONObject.parseObject(wxpubUser.getPriRewardRules(), new TypeReference<Map<String, PriRewardRulesDto>>(){});
        if(priRewardRules == null){
            priRewardRules = new HashMap<>();
        }

        //获取该运营商开启的产品模块
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(wxpubUserUpdatePriRewardRulesDto.getMerId(), MerConfigKeyEnum.PRODUCT_SWITCH.getValue());
        if(merBaseConfig != null){
            //获取该运营商开启的产品模块
            List<String> productKeyList = JSONObject.parseArray(merBaseConfig.getVal(), String.class);
            if(productKeyList != null && productKeyList.size() > 0){
                //是否包含淘宝
                if(productKeyList.contains(ProductKeyEnum.TB.getValue())){
                    PriRewardRulesDto tbRule = wxpubUserUpdatePriRewardRulesDto.getTbRule();
//                    if(tbRule != null){
//                        Long priRuleId = tbRule.getPriRuleId();
//                        if(priRuleId == null){
//                            tbRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("tbRule", tbRule);
                }

                //是否包含京东
                if(productKeyList.contains(ProductKeyEnum.JD.getValue())){
                    PriRewardRulesDto jdRule = wxpubUserUpdatePriRewardRulesDto.getJdRule();
//                    if(jdRule != null){
//                        Long priRuleId = jdRule.getPriRuleId();
//                        if(priRuleId == null){
//                            jdRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("jdRule",jdRule);
                }

                //是否包含拼多多
                if(productKeyList.contains(ProductKeyEnum.PDD.getValue())){
                    PriRewardRulesDto pddRule = wxpubUserUpdatePriRewardRulesDto.getPddRule();
//                    if(pddRule != null){
//                        Long priRuleId = pddRule.getPriRuleId();
//                        if(priRuleId == null){
//                            pddRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("pddRule",pddRule);
                }

                //是否包含唯品会
                if(productKeyList.contains(ProductKeyEnum.VPH.getValue())){
                    PriRewardRulesDto vphRule = wxpubUserUpdatePriRewardRulesDto.getVphRule();
//                    if(vphRule != null){
//                        Long priRuleId = vphRule.getPriRuleId();
//                        if(priRuleId == null){
//                            vphRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("vphRule",vphRule);
                }

                //是否包含本地生活
                if(productKeyList.contains(ProductKeyEnum.LOCAL_LIVE.getValue())){
                    PriRewardRulesDto localLiveRule = wxpubUserUpdatePriRewardRulesDto.getLocalLiveRule();
//                    if(localLiveRule != null){
//                        Long priRuleId = localLiveRule.getPriRuleId();
//                        if(priRuleId == null){
//                            localLiveRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("localLiveRule",localLiveRule);
                }

                //是否包含抖音
                if(productKeyList.contains(ProductKeyEnum.DY.getValue())){
                    PriRewardRulesDto dyRule = wxpubUserUpdatePriRewardRulesDto.getDyRule();
//                    if(dyRule != null){
//                        Long priRuleId = dyRule.getPriRuleId();
//                        if(priRuleId == null){
//                            dyRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("dyRule", dyRule);
                }

                //是否包含抖音
                if(productKeyList.contains(ProductKeyEnum.KS.getValue())){
                    PriRewardRulesDto ksRule = wxpubUserUpdatePriRewardRulesDto.getKsRule();
//                    if(dyRule != null){
//                        Long priRuleId = dyRule.getPriRuleId();
//                        if(priRuleId == null){
//                            dyRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("ksRule", ksRule);
                }
            }
        }

        wxpubUser.setPriRewardRules(Tools.getStrEmpty(JSONObject.toJSONString(priRewardRules)));
        wxpubUser.setUpdateTime(DateUtil.getNowTime());

        wxpubUserMapper.updateByIdSelective(wxpubUser);
    }


    /**
     * 修改微信用户会员标签
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param userUpdateMarketingTagDto
     * @return null
     */
    public void updateSysTags(UserUpdateMarketingTagDto userUpdateMarketingTagDto){
        if(userUpdateMarketingTagDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入会员id");
        }

        WxpubUser wxpubUser = wxpubUserMapper.selectById(userUpdateMarketingTagDto.getId(), userUpdateMarketingTagDto.getMerId());

        if(wxpubUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员不存在");
        }

        wxpubUser.setSysTags(Tools.getStrEmpty(JSONObject.toJSONString(userUpdateMarketingTagDto.getSysTagList())));

        wxpubUserMapper.updateSysTags(wxpubUser);

    }

    /**
     * 加入黑名单
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxpubUserAddBlackDto
     * @return null
     */
    public void addBlackUser(WxpubUserAddBlackDto wxpubUserAddBlackDto){
        if(wxpubUserAddBlackDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WxpubUser wxpubUser = wxpubUserMapper.selectById(wxpubUserAddBlackDto.getId(), wxpubUserAddBlackDto.getMerId());

        if(wxpubUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员不存在");
        }

        Integer now = DateUtil.getNowTime();

        //查询是否已经在黑名单当中
        //id为merId_wxid
        String id = wxpubUser.getMerId() + "_" + wxpubUser.getBizUserId();
        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id, null);
        WechatBlacklistPrv wechatBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WechatBlacklistPrv.class);
        if(wechatBlacklistPrv != null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员已经在黑名单中");
        }
        //添加到全网黑名单
        if(wxpubUserAddBlackDto.getAllBackFlag() != null && wxpubUserAddBlackDto.getAllBackFlag().intValue() == 1){
            Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, wxpubUser.getBizUserId(), null);
            WechatBlacklistPub wechatBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WechatBlacklistPub.class);
            if(wechatBlacklistPub != null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员已经在共享黑名单里");
            }
        }

        if(wechatBlacklistPrv == null){
            wechatBlacklistPrv = new WechatBlacklistPrv();
            wechatBlacklistPrv.setId(id);
            wechatBlacklistPrv.setMerId(wxpubUser.getMerId());
            wechatBlacklistPrv.setDeviceUniqueId(wxpubUser.getDeviceUniqueId());
            wechatBlacklistPrv.setDeviceType(wxpubUser.getDeviceType());
            wechatBlacklistPrv.setWxid(wxpubUser.getBizUserId());
            wechatBlacklistPrv.setNickName(wxpubUser.getNickName());
            wechatBlacklistPrv.setHeadImg(wxpubUser.getHeadImg());
            wechatBlacklistPrv.setType(wxpubUserAddBlackDto.getUserBlackType());
            wechatBlacklistPrv.setCreateTime(now);
            wechatBlacklistPrv.setRemark(wxpubUserAddBlackDto.getRemark());
            wechatBlacklistPrv.setUpdateTime(now);
            elasticsearchUtil.addData(wechatBlacklistPrv, EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id);

            //添加到全网黑名单
            if(wxpubUserAddBlackDto.getAllBackFlag() != null && wxpubUserAddBlackDto.getAllBackFlag().intValue() == 1){
                Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, wxpubUser.getBizUserId(), null);
                WechatBlacklistPub wechatBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WechatBlacklistPub.class);
                //全网黑名单中不存在
                if(wechatBlacklistPub == null){
                    wechatBlacklistPub = new WechatBlacklistPub();
                    BeanUtils.copyProperties(wechatBlacklistPrv, wechatBlacklistPub);
                    wechatBlacklistPub.setId(wxpubUser.getBizUserId());
                    wechatBlacklistPub.setCreateTime(now);
                    wechatBlacklistPub.setUpdateTime(now);
                    //数据来源(0运营商共享 1官方采集-免费  2收费名单)
                    wechatBlacklistPub.setSource(0);
                    //增加到全网黑名单
                    elasticsearchUtil.addData(wechatBlacklistPub, EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, wxpubUser.getBizUserId());
                }
            }
        }

        try {
            //延迟0.5秒
            Thread.sleep(500);
        }catch (Exception e){

        }
    }

    /**
     * 用户发送消息
     *
     * @param wxpubUserSendMsgDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void sendMessageToOneUser(WxpubUserSendMsgDto wxpubUserSendMsgDto) {

        if (wxpubUserSendMsgDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户ID参数不能为空");
        }

        WxpubUser wxpubUser = wxpubUserMapper.selectById(wxpubUserSendMsgDto.getId(), wxpubUserSendMsgDto.getMerId());

        if (wxpubUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户不存在");
        }

        if (StringUtils.isBlank(wxpubUserSendMsgDto.getMessage())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "发送消息为空 ");
        }

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(wxpubUser.getDeviceUniqueId(), wxpubUser.getDeviceType(), wxpubUserSendMsgDto.getMerId());
        if (device == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户绑定的机器人id不存在");
        }

        //调用API服务发送消息
        // TODO: 2022-4-21 10:01:17  发送消息
        //发送MQ消息
        MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
        NoticeMsgDto  noticeMsgDto = new NoticeMsgDto();
        msgDto.setContent(noticeMsgDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(device.getRecvmsgType());
        msgDto.setDeviceUniqueId(wxpubUser.getDeviceUniqueId());
        msgDto.setMerId(wxpubUser.getMerId());
        msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
        noticeMsgDto.setContent(wxpubUserSendMsgDto.getMessage());
        noticeMsgDto.setBizUserId(wxpubUser.getBizUserId());
        noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
        noticeMsgDto.setGroupId(null);
        noticeMsgDto.setNickName(wxpubUser.getNickName());
        noticeMsgDto.setMsgSource(1);
        noticeMsgDto.setDelay(0);
        noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
        noticeMsgPushProducerService.sendMessage(msgDto);
    }


    /**
     * 修改互通的的个人微信会员所在的机器人
     */
    public void updateInterflowWechatUser(UpdateWechatUserDto updateWechatUserDto){
        //公众号用户id
        Long id = updateWechatUserDto.getId();
        //对应新的机器人id
        Long wechatDeviceUniqueId = updateWechatUserDto.getWechatDeviceUniqueId();

        if(id == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "个人微信id不能为空");
        }

        if(wechatDeviceUniqueId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人id不能为空");
        }
        WxpubUser wxpubUser = wxpubUserMapper.selectById(id, updateWechatUserDto.getMerId());
        if(wxpubUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        String uzaiUnionId = wxpubUser.getUzaiUnionId();

        if(StringUtils.isBlank(uzaiUnionId)){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户还未互通个人微信会员");
        }

        WechatUser wechatUser = wechatUserMapper.selectByUzaiUnionId(uzaiUnionId, updateWechatUserDto.getMerId());
        if(wechatUser == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户还未互通个人微信会员");
        }

//        WxpubInfoEntity wxpubInfoEntity = .queryObject(wechatDeviceUniqueId);
//        if(wxpubInfoEntity == null){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在或已删除");
//        }
//        wechatUser.setDeviceUniqueId(wechatDeviceUniqueId);
//        wechatUserMapper.updateDevice(wechatUser);
    }

    /**
     * 修改会员订阅信息
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param updateSubscribeInfoDto
     * @return null
     */
    public void updateSubscribeInfo(UpdateSubscribeInfoDto updateSubscribeInfoDto){
        //公众号用户id
        Long id = updateSubscribeInfoDto.getId();

        WxpubUser wxpubUser = wxpubUserMapper.selectById(id, updateSubscribeInfoDto.getMerId());
        if(wxpubUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        wxpubUser.setSubscribeInfo(updateSubscribeInfoDto.getSubscribeInfo());
        wxpubUserMapper.updateSubscribeInfo(wxpubUser);
    }

    /**
     * 修改会员营销奖励
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param updateMarketingRewardDto
     * @return null
     */
    @Transactional
    public void updateMarketingReward(UpdateMarketingRewardDto updateMarketingRewardDto){
        //公众号微信用户id
        Long userId = updateMarketingRewardDto.getId();

        WxpubUser wxpubUser = wxpubUserMapper.selectById(userId, updateMarketingRewardDto.getMerId());

        if(wxpubUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //页面修改的营销策略
        MarketingRewardVo marketingReward = updateMarketingRewardDto.getMarketingReward();
        if(marketingReward == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入营销奖励信息");
        }

        //获取该会员的营销策略数据
        String uzai_marketing_reward_info = EsIndexName.UZAI_MARKETING_REWARD_INFO;
        String marketingRewardId = org.apache.commons.lang3.StringUtils.join(wxpubUser.getId(), wxpubUser.getRegSource());
        Map<String, Object> dataMap = elasticsearchUtil.searchDataById(uzai_marketing_reward_info, marketingRewardId, null);
        MarketingRewardVo marketingRewardVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), MarketingRewardVo.class);
        if(marketingRewardVo == null){
            marketingRewardVo = new MarketingRewardVo();
        }
        marketingRewardVo.setId(marketingRewardId);

        String tradeno_old = org.apache.commons.lang3.StringUtils.join(userId, wxpubUser.getRegSource());
        int now = DateUtil.getNowTime();

        //添加好友奖励
        if(marketingReward.getAddRe() != null){
            MarketingRewardVo.ReDetail addRe =  marketingReward.getAddRe();
            //ES缓存对象
            MarketingRewardVo.ReDetail addReVo =  marketingRewardVo.getAddRe();
            if(addReVo == null){
                addReVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(addRe, addReVo, CopyOptions.create().ignoreNullValue());
            addReVo.setUserId(wxpubUser.getId());
            //更新会员的营销奖励数据
            marketingRewardVo.setAddRe(addReVo);

            //奖励状态 0未奖励，1已奖励,
            if(addRe.getStatus() != null && addRe.getStatus() == 0){ //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if(Tools.getDouble(addRe.getReBal()) > 0 || Tools.getInteger(addRe.getReInte()) > 0){//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_REGIST.getValue(), tradeno_old);
                    if(userAccDetail != null){ //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = org.apache.commons.lang3.StringUtils.join(tradeno_old, RedPackTypeEnum.REGISTER_GIVE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wxpubUser.getMerId());
                    if(redPacket != null){ //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //绑定上级，奖励下级
        if(marketingReward.getBindRe() != null){
            MarketingRewardVo.ReDetail bindRe =  marketingReward.getBindRe();
            //ES缓存对象
            MarketingRewardVo.ReDetail bindReVo =  marketingRewardVo.getBindRe();
            if(bindReVo == null){
                bindReVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(bindRe, bindReVo, CopyOptions.create().ignoreNullValue());
            bindReVo.setUserId(wxpubUser.getId());
            //更新会员的营销奖励数据
            marketingRewardVo.setBindRe(bindReVo);

            //奖励状态 0未奖励，1已奖励,
            if(bindRe.getStatus() != null && bindRe.getStatus() == 0){ //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if(Tools.getDouble(bindRe.getReBal()) > 0 || Tools.getInteger(bindRe.getReInte()) > 0){//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_INVITE.getValue(), tradeno_old);
                    if(userAccDetail != null){ //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = org.apache.commons.lang3.StringUtils.join(tradeno_old, RedPackTypeEnum.REWARD_INVITE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wxpubUser.getMerId());
                    if(redPacket != null){ //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //绑定上级，奖励上级
        if(marketingReward.getBindReParent() != null){
            MarketingRewardVo.ReDetail bindReParent =  marketingReward.getBindReParent();
            //ES缓存对象
            MarketingRewardVo.ReDetail bindReParentVo =  marketingRewardVo.getBindReParent();
            if(bindReParentVo == null){
                bindReParentVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(bindReParent, bindReParentVo, CopyOptions.create().ignoreNullValue());
            bindReParentVo.setUserId(wxpubUser.getParentId());
            //更新会员的营销奖励数据
            marketingRewardVo.setBindReParent(bindReParentVo);

            //奖励状态 0未奖励，1已奖励,
            if(bindReParent.getStatus() != null && bindReParent.getStatus() == 0){ //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if(Tools.getDouble(bindReParent.getReBal()) > 0 || Tools.getInteger(bindReParent.getReInte()) > 0){//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_INVITE_PARENT.getValue(), tradeno_old);
                    if(userAccDetail != null){ //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = org.apache.commons.lang3.StringUtils.join(tradeno_old, RedPackTypeEnum.REWARD_INVITE_PARENT.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wxpubUser.getMerId());
                    if(redPacket != null){ //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //绑定代理，奖励代理
        if(marketingReward.getBindReAgent() != null){
            MarketingRewardVo.ReDetail bindReAgent =  marketingReward.getBindReAgent();
            //ES缓存对象
            MarketingRewardVo.ReDetail bindReAgentVo =  marketingRewardVo.getBindReAgent();
            if(bindReAgentVo == null){
                bindReAgentVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(bindReAgent, bindReAgentVo, CopyOptions.create().ignoreNullValue());
            bindReAgentVo.setUserId(wxpubUser.getAgentId());
            //更新会员的营销奖励数据
            marketingRewardVo.setBindReAgent(bindReAgentVo);

            //奖励状态 0未奖励，1已奖励,
            if(bindReAgent.getStatus() != null && bindReAgent.getStatus() == 0){ //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if(Tools.getDouble(bindReAgent.getReBal()) > 0 || Tools.getInteger(bindReAgent.getReInte()) > 0){//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_ORDER_AGENT.getValue(), tradeno_old);
                    if(userAccDetail != null){ //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = org.apache.commons.lang3.StringUtils.join(tradeno_old, RedPackTypeEnum.REWARD_INVITE_AGENT.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wxpubUser.getMerId());
                    if(redPacket != null){ //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //绑定合伙人，奖励合伙人
        if(marketingReward.getBindRePartner() != null){
            MarketingRewardVo.ReDetail bindRePartner =  marketingReward.getBindRePartner();
            //ES缓存对象
            MarketingRewardVo.ReDetail bindRePartnerVo =  marketingRewardVo.getBindRePartner();
            if(bindRePartnerVo == null){
                bindRePartnerVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(bindRePartner, bindRePartnerVo, CopyOptions.create().ignoreNullValue());
            bindRePartnerVo.setUserId(wxpubUser.getPartnerId());
            //更新会员的营销奖励数据
            marketingRewardVo.setBindRePartner(bindRePartnerVo);

            //奖励状态 0未奖励，1已奖励,
            if(bindRePartner.getStatus() != null && bindRePartner.getStatus() == 0){ //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if(Tools.getDouble(bindRePartner.getReBal()) > 0 || Tools.getInteger(bindRePartner.getReInte()) > 0){//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_ORDER_PARTNER.getValue(), tradeno_old);
                    if(userAccDetail != null){ //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = org.apache.commons.lang3.StringUtils.join(tradeno_old, RedPackTypeEnum.REWARD_INVITE_PARTNER.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wxpubUser.getMerId());
                    if(redPacket != null){ //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //首查奖励
        if(marketingReward.getFirstQueryRe() != null){
            MarketingRewardVo.ReDetail firstQueryRe =  marketingReward.getFirstQueryRe();
            //ES缓存对象
            MarketingRewardVo.ReDetail firstQueryReVo =  marketingRewardVo.getFirstQueryRe();
            if(firstQueryReVo == null){
                firstQueryReVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(firstQueryRe, firstQueryReVo, CopyOptions.create().ignoreNullValue());
            firstQueryReVo.setUserId(wxpubUser.getId());
            //更新会员的营销奖励数据
            marketingRewardVo.setFirstQueryRe(firstQueryReVo);

            //奖励状态 0未奖励，1已奖励,
            if(firstQueryRe.getStatus() != null && firstQueryRe.getStatus() == 0){ //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if(Tools.getDouble(firstQueryRe.getReBal()) > 0 || Tools.getInteger(firstQueryRe.getReInte()) > 0){//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_FIRST_QUERY.getValue(), tradeno_old);
                    if(userAccDetail != null){ //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = org.apache.commons.lang3.StringUtils.join(tradeno_old, RedPackTypeEnum.FIRST_QUERY_GIVE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wxpubUser.getMerId());
                    if(redPacket != null){ //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //首单奖励
        if(marketingReward.getFirstOrderRe() != null){
            MarketingRewardVo.ReDetail firstOrderRe =  marketingReward.getFirstOrderRe();
            //ES缓存对象
            MarketingRewardVo.ReDetail firstOrderReVo =  marketingRewardVo.getFirstOrderRe();
            if(firstOrderReVo == null){
                firstOrderReVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(firstOrderRe, firstOrderReVo, CopyOptions.create().ignoreNullValue());
            firstOrderReVo.setUserId(wxpubUser.getId());
            //更新会员的营销奖励数据
            marketingRewardVo.setFirstOrderRe(firstOrderReVo);

            //奖励状态 0未奖励，1已奖励,
            if(firstOrderRe.getStatus() != null && firstOrderRe.getStatus() == 0){ //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if(Tools.getDouble(firstOrderRe.getReBal()) > 0 || Tools.getInteger(firstOrderRe.getReInte()) > 0){//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_FIRST_ORDER.getValue(), tradeno_old);
                    if(userAccDetail != null){ //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = org.apache.commons.lang3.StringUtils.join(tradeno_old, RedPackTypeEnum.FIRST_ORDER_GIVE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wxpubUser.getMerId());
                    if(redPacket != null){ //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //首次收货奖励
        if(marketingReward.getFirstSettledRe() != null){
            MarketingRewardVo.ReDetail firstSettledRe =  marketingReward.getFirstSettledRe();
            //ES缓存对象
            MarketingRewardVo.ReDetail firstSettledReVo =  marketingRewardVo.getFirstSettledRe();
            if(firstSettledReVo == null){
                firstSettledReVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(firstSettledRe, firstSettledReVo, CopyOptions.create().ignoreNullValue());
            firstSettledReVo.setUserId(wxpubUser.getId());
            //更新会员的营销奖励数据
            marketingRewardVo.setFirstSettledRe(firstSettledReVo);

            //奖励状态 0未奖励，1已奖励,
            if(firstSettledRe.getStatus() != null && firstSettledRe.getStatus() == 0){ //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if(Tools.getDouble(firstSettledRe.getReBal()) > 0 || Tools.getInteger(firstSettledRe.getReInte()) > 0){//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_FIRST_SETTLE.getValue(), tradeno_old);
                    if(userAccDetail != null){ //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = org.apache.commons.lang3.StringUtils.join(tradeno_old, RedPackTypeEnum.FIRST_SETTLED_GIVE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wxpubUser.getMerId());
                    if(redPacket != null){ //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //修改营销数据ES
        elasticsearchUtil.addDataForObjectSerializer(marketingRewardVo, uzai_marketing_reward_info, tradeno_old);
    }

}
